python实现的一只从百度开始不断搜索的小爬虫
#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']*?[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()
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
专题推荐
-
独孤九贱-php全栈开发教程
全栈 170W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
-
玉女心经-web前端开发教程
入门 80W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
-
天龙八部-实战开发教程
实战 120W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论