468 views

BFS爬虫的Python实现

宽度优先是爬虫中使用最为广泛的一种策略,更详细的可以查看宽度优先爬虫。

下午没事干,正好练练python,顺便发本月第一篇blog。。。代码简单实现了抓取网页的中超链接,就是a标签的href,其他像简单的img标签也类似。

#!/usr/bin/python 
#-*- coding: UTF-8 -*- 
from bs4 import BeautifulSoup 
import urllib2
#定义URL队列
class URLQuence:
    def __init__(self):
        #已访问的url List
        self.visted=[]
        #未访问的url List
        self.unVisited=[]
    #添加到未访问List
    def addUnvisitedUrl(self,url):
        if url[-1]=="/":
            url2=url[:-1]
        else:
            url2=url+"/"
        if url not in self.visted and \
            url not in self.unVisited and \
            url2 not in self.visted and \
            url2 not in self.unVisited:
            #插入头部
            self.unVisited.insert(0,url)
class MySpider:
    def __init__(self):
        self.urlQuence=URLQuence();
    def addURL(self,url):
        self.urlQuence.addUnvisitedUrl(url)
    #开始抓取
    def start(self):
        while self.urlQuence.unVisited:
            #url出列
            url=self.urlQuence.unVisited.pop()    
            #添加到已访问URL
            self.urlQuence.visted.append(url)
            urls=self.getURL(url)
            #添加到未访问URL
            for i in urls:
                self.urlQuence.addUnvisitedUrl(i)
            print self.urlQuence.unVisited
    #得到该url下的所有urls
    def getURL(self,url):
        urls=[]
        html=self.getSourceCode(url)
        if html:
            soup = BeautifulSoup(html)
            content=soup.findAll("a")
            for i in content:
                url=i["href"]
                if url and url[0:4]=="http":
                    urls.append(url)
        return urls
    #得到源码
    def getSourceCode(self,url):
        try:
            html=urllib2.urlopen(url).read()
        except:
            return None
        return html
if __name__=="__main__":
    url="http://127.0.0.1"
    mySpider=MySpider()
    mySpider.addURL(url)
    print "start"
    mySpider.start()
    print mySpider.urlQuence.visted
    print "over"

未定义队列的深度,导致爬自己的yilee.info时无法中断。。。

这是第一次爬之后的unvisited列表,列表末尾为第一个进入的。

这是自己随便加的几个测试页面。

期间遇到了BeautifulSoup中文解码问题,老是提醒转码错误,不过后来就没了。。。不懂正则表达式,这个真够麻烦的,代码可能很cuo,不过实现了BFS抓超链接最简单的功能。

Fork me on GitHub

4 thoughts on “BFS爬虫的Python实现

  1. BeautifulSoup是个好东西

    今天刚看到,Scrapy采用的是深度优先遍历…不过对于定向抓取来看,影响不大

  2. Pingback: 宽度优先爬虫 | 天堂皓月

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">