爬虫爬取百度词条
頁(yè)面是隨時(shí)升級(jí)的,所以現(xiàn)在的鏈接不代表以后的鏈接,但是萬(wàn)變不離其宗,只要學(xué)會(huì)解析頁(yè)面,那么就能走的更遠(yuǎn)。
碼云鏈接:https://gitee.com/ALADL/baike_spider.git
from baike_spider import url_manager,html_downloader, html_parser, html_outputerclass SpiderMain(object):def __init__(self):# 初始化各個(gè)對(duì)象self.urls = url_manager.UrlManager()# url管理器self.downloader = html_downloader.HtmlDownloader()# 下載器self.parser = html_parser.HtmlParser()# 解析器self.outputer = html_outputer.HtmlOutputer()# 輸出器def craw(self, root_url):count = 1# 將入口(root)url添加進(jìn)管理器 self.urls.add_new_url(root_url)# 當(dāng)管理器中有了url之后,我們就可以啟動(dòng)循環(huán)while self.urls.has_new_url():# 為了防止無(wú)效的url,這里異常處理try:# 獲取一個(gè)帶爬取的urlnew_url = self.urls.get_new_url()# 輔助,打印一下當(dāng)前print('craw %d:%s'%(count,new_url))# 啟用下載器下載頁(yè)面html_cont = self.downloader.download(new_url)# 調(diào)用解析器解析頁(yè)面,得到新的url和新的數(shù)據(jù)new_urls,new_data = self.parser.paser(new_url,html_cont)# 分別處理,新的url添加進(jìn)url管理器 self.urls.add_new_urls(new_urls)# 同時(shí)收集數(shù)據(jù) self.outputer.collect_data(new_data)# 先爬取1000個(gè)urlif count == 1000:breakcount += 1except:print("craw failed")# 調(diào)用outputer來(lái)處理數(shù)據(jù) self.outputer.output_html()if __name__ == '__main__':root_url = 'https://baike.baidu.com/item/%E8%8B%8F%E8%BD%BC/53906#hotspotmining'# main函數(shù)中復(fù)制要爬取的頁(yè)面obj_spider = SpiderMain()obj_spider.craw(root_url)?
轉(zhuǎn)載于:https://www.cnblogs.com/ALADL/p/9671690.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
- 上一篇: 如何在终端编译C++代码
- 下一篇: python 约束与异常处理