运用BeautifulSoup抓取网页的链接

来源:互联网 发布:oee计算软件 编辑:程序博客网 时间:2024/06/18 13:22

之前一直都是做前端,不知道搜索引擎后台核心是怎样实现。今天看到bd内部的spider资料,决定运用先前学过的python模拟一把,把指定网页的a标签中的href提取出来。

运用到扩展模块BeautifulSoup(http://www.crummy.com/software/BeautifulSoup/)。

BeautifulSoup的功能很强大,能方便对HTML和XML的文本处理。可以轻易捕捉到tag和className。

程序实现的原理很简单,先把网页提取出来,再提取a标签,再过滤出href,最后完善一下文本。

代码如下:

 

View Code
复制代码
 1 from BeautifulSoup import BeautifulSoup 2 import urllib2 3 import re 4  5 def grabHref(url,localfile): 6     html = urllib2.urlopen(url).read() 7     html = unicode(html,'gb2312','ignore').encode('utf-8','ignore') 8     content = BeautifulSoup(html).findAll('a') 9     myfile = open(localfile,'w')10     pat = re.compile(r'href="([^"]*)"')11     pat2 = re.compile(r'http')12     for item in content:13         h = pat.search(str(item))14         href = h.group(1)15         if pat2.search(href):16             ans = href17         else:18             ans = url+href19         myfile.write(ans)20         myfile.write('\r\n')21         print ans22     myfile.close()23     24 def main():25     url = "http://www.hao123.com"26     localfile = 'aHref.txt'27     grabHref(url,localfile)28 if __name__=="__main__":29     main()
复制代码

其中比较dt的是match和search的正则表达式判定,之前这方面做得比较少,上网查了一下原来两者的区别是 match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none。

然后就是扩展模块的调用,把下载得到的文件夹setup之后得到BeautifulSoup.py及其编译文件。把两者放到安装目录的lib下就好了。不能只放在BeautifulSoup文件夹下。导入源文件时是用from BeautifulSoup import BeautifulSoup就直接调用BeautifulSoup.findAll()方法,否则导入时是import BeautifulSoup的话,调用方法就需要写成BeautifulSoup.BeautifulSoup().findAll().

程序运行后会得到一个aHref.txt的文件,并且在console中打印hao123的所有链接。搜索引擎的spider就是再从这堆链接中继续递归去爬行。当然真正实现起来肯定会想得更全面,做得更精的, 而且涉及到的算法很复杂。这里只是提取网页链接而已。

原创粉丝点击