python 网络爬虫(二) BFS不断抓URL并放到文件中
来源:互联网 发布:申请淘宝信用借钱 编辑:程序博客网 时间:2024/06/06 02:56
上一篇的python 网络爬虫(一) 简单demo 还不能叫爬虫,只能说基础吧,因为它没有自动化抓链接的功能。
本篇追加如下功能:
【1】广度优先搜索不断抓URL,直到队列为空
【2】把所有的URL写入文件中
【3】对于不可访问或错误访问的URL,有try except 处理
spider.py
# -*- coding: cp936 -*-import urllib,Queue,sgmllib,re,osclass URLList(sgmllib.SGMLParser): def reset(self): sgmllib.SGMLParser.reset(self) #maxsize < 1 表示无穷队列 self.URLqueue = Queue.Queue(maxsize = -1) def start_a(self,attrs): href = [v for k,v in attrs if k == 'href'] if href: for u in href: #判断URL是不是正确的,href都必须有"http://" pat = re.compile(r'http://(.+?)') #False,0,'',[],{},()都可以视为假,也可以用len()==0判断列表为空 if len(re.findall(pat,u)) == 0: continue self.URLqueue.put(u) def getURLList(url,parser): try: URLdata = urllib.urlopen(url) parser.feed(URLdata.read()) URLdata.close() except: return startURL = "http://www.baidu.com"parser = URLList()getURLList(startURL,parser)outfile = startURL[7:len(startURL)]+".txt"out = open(outfile,'w+')try: #BFS while parser.URLqueue.empty() == False: url = parser.URLqueue.get() print url out.writelines(url+'\n') getURLList(url,parser)finally: parser.close() out.close()
- python 网络爬虫(二) BFS不断抓URL并放到文件中
- python爬虫(Python读取TXT文件中的URL并下载文件)
- python网络爬虫(二)
- python网络爬虫(二)
- java网络爬虫学习记录(二)抓包分析
- [Python]网络爬虫(五):抓站经验技巧
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- c++类名()创建临时对象
- 机器视觉开源代码集合
- uuuuuuuuuu
- 程序员是应用安全的第一道闸
- Linux mysql load_file常用路径
- python 网络爬虫(二) BFS不断抓URL并放到文件中
- Qt中xml的读写
- 电话归属地查询的实现
- c++ 调用dll函数,导出类中的成员函数
- 如何合并文件中的内容?
- hdu4451(组合数)
- 归纳整理业务
- Python基础 2----Python 基础语法
- Hdu 4714 Tree2cycle - DFS