python实现的一只从百度开始不断搜索的小爬虫
2013-09-08 10:07
741 查看
文中用到了BeautifulSoup这个库, 目的是处理html文档分析的, 因为我只是提取了title的关键字,所以可以用正则表达式代替, 还有一个库是jieba, 这个库是中文分词的作用, 再有一个库是 chardet, 用来判断字符的编码, 本想多线程的, 但是自认为被搞糊涂了,就放弃了
复制代码 代码如下:
复制代码 代码如下:
#coding:utf-8 import re import urllib import urllib2 import sys import time import Queue import thread import threading import jieba import chardet from BeautifulSoup import BeautifulSoup as BS DEEP = 1000 LOCK = threading.Lock() PATH = "c:\\test\\" urlQueue = Queue.Queue() def pachong(): url = 'http://www.baidu.com' return url def getPageUrl(html): reUrl = re.compile(r'<\s*[Aa]{1}\s+[^>]*?[Hh][Rr][Ee][Ff]\s*=\s*[\"\']?([^>\"\']+)[\"\']?.*?>') urls = reUrl.findall(html) for url in urls: if len(url) > 10: if url.find('javascript') == -1: urlQueue.put(url) def getContents(url): try: url = urllib2.quote(url.split('#')[0].encode('utf-8'), safe = "%/:=&?~#+!$,;'@()*[]") req = urllib2.urlopen(url) res = req.read() code = chardet.detect(res)['encoding'] #print #print code res = res.decode(str(code), 'ignore') res = res.encode('gb2312', 'ignore') code = chardet.detect(res)['encoding'] #print code #print res return res except urllib2.HTTPError, e: print e.code return None except urllib2.URLError, e: print str(e) return None def writeToFile(html, url): fp = file(PATH + str(time.time()) + '.html', 'w') fp.write(html) fp.close() def getKeyWords(html): code = chardet.detect(html)['encoding'] if code == 'ISO-8859-2': html.decode('gbk', 'ignore').encode('gb2312', 'ignore') code = chardet.detect(html)['encoding'] soup = BS(html, fromEncoding="gb2312") titleTag = soup.title titleKeyWords = titleTag.contents[0] cutWords(titleKeyWords) def cutWords(contents): print contents res = jieba.cut_for_search(contents) res = '\n'.join(res) print res res = res.encode('gb2312') keyWords = file(PATH + 'cutKeyWors.txt', 'a') keyWords.write(res) keyWords.close() def start(): while urlQueue.empty() == False: url = urlQueue.get() html = getContents(url) getPageUrl(html) getKeyWords(html) #writeToFile(html, url) if __name__ == '__main__': startUrl = pachong() urlQueue.put(startUrl) start()
相关文章推荐
- python实现的一只从百度开始不断搜索的小爬虫
- python实现的一只从百度开始不断搜索的小爬虫
- 一只从百度开始不断搜索的小爬虫
- 利用python爬取海量疾病名称百度搜索词条目数的爬虫实现
- 利用python爬取海量疾病名称百度搜索词条目数的爬虫实现
- [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图
- 第三百六十八节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索的自动补全功能
- [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图
- Python爬虫爬取百度搜索结果——邮箱地址
- 通俗易懂的分析如何用Python实现一只小爬虫,爬取拉勾网的职位信息
- C++和python如何获取百度搜索结果页面下信息对应的真实链接(百度搜索爬虫,可指定页数)
- 第三百七十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现我的搜索以及热门搜索
- python爬虫(11)身边的搜索专家——获取百度搜索结果
- Python实现百度搜索并保存到本地示例,Python实现百度搜索
- 第三百七十节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索结果分页
- python爬虫实现网盘资源搜索
- python 爬虫百度搜索结果
- python实现提取百度搜索结果的方法
- Python实现抓取百度搜索结果页的网站标题信息
- Python实现抓取百度搜索结果页的网站标题信息