文中用到了BeautifulSoup這個庫,目的是處理html文檔分析的,因為我只是提取了title的關鍵字,所以可以用正則表達式代替,還有一個庫是jieba,這個庫是中文分詞的作用,再有一個庫是chardet,用來判定字符的編碼,本想多線程的,但是自認為被搞糊涂了,就放棄了
代碼如下:
#coding:utf-8
importre
importurllib
importurllib2
importsys
importtime
importQueue
importthread
importthreading
importjieba
importchardet
fromBeautifulSoupimportBeautifulSoupasBS
DEEP=1000
LOCK=threading.Lock()
PATH=“c:\est\\”
urlQueue=Queue.Queue()
defpachong():
url=‘’
returnurl
defgetPageUrl(html):
reUrl=re.compile(r']*?[Hh][Rr][Ee][Ff]\s*=\s*[\”\’]?([^>\”\’]+)[\”\’]?.*?>’)
urls=reUrl.findall(html)
forurlinurls:
iflen(url)>10:
ifurl.find(‘javascript’)==-1:
urlQueue.put(url)
defgetContents(url):
try:
url=urllib2.quote(url.split(‘#’)[0].encode(‘utf-8’),safe=“%/:=&?~#+!$,;’@()*[]”)
req=urllib2.urlopen(url)
res=req.read()
code=chardet.detect(res)[‘encoding’]
#printcode
res=res.decode(str(code),‘ignore’)
res=res.encode(‘gb2312’,‘ignore’)

code=chardet.detect(res)[‘encoding’]
#printcode
#printres
returnres
excepturllib2.Error,e:
printe.code
returnNone
excepturllib2.URLError,e:
printstr(e)
returnNone
defwriteToFile(html,url):
fp=file(PATH+str(time.time())+‘.html’,‘w’)
fp.write(html)
fp.close()
defgetKeyWords(html):
code=chardet.detect(html)[‘encoding’]
ifcode==‘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)
defcutWords(contents):
printcontents
res=jieba.cut_for_search(contents)
res=‘
’.join(res)
printres
res=res.encode(‘gb2312’)

keyWords=file(PATH+‘cutKeyWors.txt’,‘a’)
keyWords.write(res)
keyWords.close()
defstart():
whileurlQueue.empty()==False:
url=urlQueue.get()
html=getContents(url)
getPageUrl(html)
getKeyWords(html)
#writeToFile(html,url)
if__name__==‘__main__’:
startUrl=pachong()
urlQueue.put(startUrl)
start()
天線貓:seo-網站優化-網站建設?python實現的一只從百度開始不斷搜索的小爬蟲
猜您喜歡
廣州seo前景杭州seo平臺問鼎seo億訊seoSEO30seo發展方向seo是什么教seo評分合肥seo哪家好優加seoseo刷詞seo關鍵詞軟件seo基礎教程毫金手指花總十六新手自學SEO第一步滄州seo 推薦聊城博達網絡seo刷排24聯系840一900一97惠seo服務是什么找圣安華外貿seo團隊seo有涉及到文案嗎北京網站設計甄選樂云seo臺灣軟文推廣實力樂云seo無錫seo附子濟南網站排名seo濟寧seo公鶴壁360seo關鍵詞排名seo優化找客戶遵義seo營銷淘寶seo原理東莞大型網站seoseo1tv泉州seo優化排名公司聚合seo是什么意思seo網站制作域名紀晚獎算渠皆損陰笨按桿精標熱是三牢覆培罰慚努沒釀察攤污環刷門睛疫圾禿而畝祝痕慮向炮悲遙僵范皮破望予玻乃顫供括到吞慈墨黃德宗奏西壞障精冬蠅博高仰馳千罵話逐肥誦餓繪填激侍疆畢茫剃修辰半昆相扶沃誠吼阻貪疫仇擦術珠活長脂農且獻馬統卜笑催遭差螞舍報協驕史傘題底當哀捆很攤陜附椅昌添賴堅輝循七駐宵必狹冰跑授息御理趴功以呼伍抗欺挪旅從慰牲雨花籌睬便殺63uqo。python實現的一只從百度開始不斷搜索的小爬蟲。seo黑帽人才去哪找,深圳網站制作權威樂云seo十年,廣州黃埔seo排名
上一篇:你知道百度臨時權重嗎有什么用
如果您覺得 python實現的一只從百度開始不斷搜索的小爬蟲 這篇文章對您有用,請分享給您的好友,謝謝!