运用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,最后完善一下文本。
代码如下:
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就是再从这堆链接中继续递归去爬行。当然真正实现起来肯定会想得更全面,做得更精的, 而且涉及到的算法很复杂。这里只是提取网页链接而已。
- 运用BeautifulSoup抓取网页的链接
- 运用BeautifulSoup抓取网页的链接
- python 抓取网页--用BeautifulSoup
- 使用Python+selenium+BeautifulSoup抓取动态网页的关键信息
- BeautifulSoup的简单运用
- 抓取http网页的全部链接
- 抓取网页链接的php类:snoopy
- html抓取网页链接的例子
- python beautifulsoup多线程分析抓取网页
- BeautifulSoup+正则+Python 抓取网页数据
- python beautifulsoup 抓取网页正文内容
- python beautifulsoup多线程分析抓取网页
- python : BeautifulSoup 网页 table 抓取实例
- 抓取网页中的链接
- 抓取网页中的链接
- 抓取网页中的链接
- Python抓取网页链接
- Python抓取网页链接
- 修改 HTTP 输出 (myModule)
- 终于能写博客了 来到csdn的第一篇博客
- 重写URL
- Linux中忘记root密码的解决方法
- 实现本网站图片保护功能 (访问的图片加水印)
- 运用BeautifulSoup抓取网页的链接
- openmp学习笔记
- Android中GridView设置边框
- 人生规划
- 黑马程序员——java面向对象(异常篇)
- 建造者模式——创建型模式之三
- 羊皮卷之九-我现在就付诸行动(中英对照)
- 南阳理工学院信息检索平台
- 一张专家推荐的最健康的作息时间表