Python爬蟲實(shí)現(xiàn)爬取百度百科詞條功能實(shí)例
本文實(shí)例講述了Python爬蟲實(shí)現(xiàn)爬取百度百科詞條功能。分享給大家供大家參考,具體如下:
爬蟲是一個(gè)自動(dòng)提取網(wǎng)頁的程序,它為搜索引擎從萬維網(wǎng)上下載網(wǎng)頁,是搜索引擎的重要組成。爬蟲從一個(gè)或若干初始網(wǎng)頁的URL開始,獲得初始網(wǎng)頁上的URL,在抓取網(wǎng)頁的過程中,不斷從當(dāng)前頁面上抽取新的URL放入隊(duì)列,直到滿足系統(tǒng)的一定停止條件。爬蟲的工作流程較為復(fù)雜,需要根據(jù)一定的網(wǎng)頁分析算法過濾與主題無關(guān)的鏈接,保留有用的鏈接并將其放入等待抓取的URL隊(duì)列。然后,它將根據(jù)一定的搜索策略從隊(duì)列中選擇下一步要抓取的網(wǎng)頁URL,并重復(fù)上述過程,直到達(dá)到系統(tǒng)的某一條件時(shí)停止。另外,所有被爬蟲抓取的網(wǎng)頁將會(huì)被系統(tǒng)存貯,進(jìn)行一定的分析、過濾,并建立索引,以便之后的查詢和檢索。常見的爬蟲框架有Scrapy等。
自定義爬蟲程序一般包含:URL管理器、網(wǎng)頁下載器、網(wǎng)頁解析器、輸出處理器。
以下我寫了一個(gè)爬取百度百科詞條的實(shí)例。
爬蟲主程序入口
from crawler_test.html_downloader import UrlDownLoader from crawler_test.html_outer import HtmlOuter from crawler_test.html_parser import HtmlParser from crawler_test.url_manager import UrlManager # 爬蟲主程序入口 class MainCrawler(): def __init__(self): # 初始值,實(shí)例化四大處理器:url管理器,下載器,解析器,輸出器 self.urls = UrlManager() self.downloader = UrlDownLoader() self.parser = HtmlParser() self.outer = HtmlOuter() # 開始爬蟲方法 def start_craw(self, main_url): print('爬蟲開始...') count = 1 self.urls.add_new_url(main_url) while self.urls.has_new_url(): try: new_url = self.urls.get_new_url() print('爬蟲%d,%s' % (count, new_url)) html_cont = self.downloader.down_load(new_url) new_urls, new_data = self.parser.parse(new_url, html_cont) # 將解析出的url放入url管理器,解析出的數(shù)據(jù)放入輸出器中 self.urls.add_new_urls(new_urls) self.outer.conllect_data(new_data) if count >= 10:# 控制爬取的數(shù)量 break count += 1 except: print('爬蟲失敗一條') self.outer.output() print('爬蟲結(jié)束。') if __name__ == '__main__': main_url = 'https://baike.baidu.com/item/Python/407313' mc = MainCrawler() mc.start_craw(main_url)
URL管理器
# URL管理器 class UrlManager(): def __init__(self): self.new_urls = set() # 待爬取 self.old_urls = set() # 已爬取 # 添加一個(gè)新的url def add_new_url(self, url): if url is None: return elif url not in self.new_urls and url not in self.old_urls: self.new_urls.add(url) # 批量添加url def add_new_urls(self, urls): if urls is None or len(urls) == 0: return else: for url in urls: self.add_new_url(url) # 判斷是否有url def has_new_url(self): return len(self.new_urls) != 0 # 從待爬取的集合中獲取一個(gè)url def get_new_url(self): new_url = self.new_urls.pop() self.old_urls.add(new_url) return new_url
網(wǎng)頁下載器
from urllib import request # 網(wǎng)頁下載器 class UrlDownLoader(): def down_load(self, url): if url is None: return None else: rt = request.Request(url=url, method='GET') # 發(fā)GET請求 with request.urlopen(rt) as rp: # 打開網(wǎng)頁 if rp.status != 200: return None else: return rp.read() # 讀取網(wǎng)頁內(nèi)容
網(wǎng)頁解析器
import re from urllib import parse from bs4 import BeautifulSoup # 網(wǎng)頁解析器,使用BeautifulSoup class HtmlParser(): # 每個(gè)詞條中,可以有多個(gè)超鏈接 # main_url指url公共部分,如“https://baike.baidu.com/” def _get_new_url(self, main_url, soup): # baike.baidu.com/ # <a target="_blank" href="/item/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E8%AF%AD%E8%A8%80" rel="external nofollow" >計(jì)算機(jī)程序設(shè)計(jì)語言</a> new_urls = set() # 解析出main_url之后的url部分 child_urls = soup.find_all('a', href=re.compile(r'/item/(\%\w{2})+')) for child_url in child_urls: new_url = child_url['href'] # 再拼接成完整的url full_url = parse.urljoin(main_url, new_url) new_urls.add(full_url) return new_urls # 每個(gè)詞條中,只有一個(gè)描述內(nèi)容,解析出數(shù)據(jù)(詞條,內(nèi)容) def _get_new_data(self, main_url, soup): new_datas = {} new_datas['url'] = main_url # <dd class="lemmaWgt-lemmaTitle-title"><h1>計(jì)算機(jī)程序設(shè)計(jì)語言</h1>... new_datas['title'] = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1').get_text() # class="lemma-summary" label-module="lemmaSummary"... new_datas['content'] = soup.find('div', attrs={'label-module': 'lemmaSummary'}, class_='lemma-summary').get_text() return new_datas # 解析出url和數(shù)據(jù)(詞條,內(nèi)容) def parse(self, main_url, html_cont): if main_url is None or html_cont is None: return soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8') new_url = self._get_new_url(main_url, soup) new_data = self._get_new_data(main_url, soup) return new_url, new_data
輸出處理器
# 輸出器 class HtmlOuter(): def __init__(self): self.datas = [] # 先收集數(shù)據(jù) def conllect_data(self, data): if data is None: return self.datas.append(data) return self.datas # 輸出為HTML def output(self, file='output_html.html'): with open(file, 'w', encoding='utf-8') as fh: fh.write('<html>') fh.write('<head>') fh.write('<meta charset="utf-8"></meta>') fh.write('<title>爬蟲數(shù)據(jù)結(jié)果</title>') fh.write('</head>') fh.write('<body>') fh.write( '<table style="border-collapse:collapse; border:1px solid gray; width:80%; word-break:break-all; margin:20px auto;">') fh.write('<tr>') fh.write('<th style="border:1px solid black; width:35%;">URL</th>') fh.write('<th style="border:1px solid black; width:15%;">詞條</th>') fh.write('<th style="border:1px solid black; width:50%;">內(nèi)容</th>') fh.write('</tr>') for data in self.datas: fh.write('<tr>') fh.write('<td style="border:1px solid black">{0}</td>'.format(data['url'])) fh.write('<td style="border:1px solid black">{0}</td>'.format(data['title'])) fh.write('<td style="border:1px solid black">{0}</td>'.format(data['content'])) fh.write('</tr>') fh.write('</table>') fh.write('</body>') fh.write('</html>')
效果(部分):
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- python 爬取百度文庫并下載(免費(fèi)文章限定)
- Python實(shí)現(xiàn)的爬取百度文庫功能示例
- 用python下載百度文庫的代碼
- python 爬蟲如何實(shí)現(xiàn)百度翻譯
- 詳解用Python爬蟲獲取百度企業(yè)信用中企業(yè)基本信息
- Python爬蟲爬取百度搜索內(nèi)容代碼實(shí)例
- Python爬蟲實(shí)現(xiàn)百度翻譯功能過程詳解
- python 爬蟲百度地圖的信息界面的實(shí)現(xiàn)方法
- python爬蟲之爬取百度音樂的實(shí)現(xiàn)方法
- python爬蟲獲取百度首頁內(nèi)容教學(xué)
- Python爬蟲實(shí)現(xiàn)百度圖片自動(dòng)下載
- Python爬蟲實(shí)例_利用百度地圖API批量獲取城市所有的POI點(diǎn)
- python實(shí)現(xiàn)百度文庫自動(dòng)化爬取
相關(guān)文章
python實(shí)現(xiàn)鬧鐘定時(shí)播放音樂功能
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)鬧鐘定時(shí)播放音樂功能,播放wav格式的音頻,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Python利用contextvars實(shí)現(xiàn)管理上下文變量
Python?在?3.7?的時(shí)候引入了一個(gè)模塊:contextvars,從名字上很容易看出它指的是上下文變量。所以本文就來和大家詳細(xì)講講如何使用contextvars實(shí)現(xiàn)管理上下文變量,需要的可以參考一下2022-07-07Python使用DPKT實(shí)現(xiàn)分析數(shù)據(jù)包
dpkt項(xiàng)目是一個(gè)Python模塊,主要用于對(duì)網(wǎng)絡(luò)數(shù)據(jù)包進(jìn)行解析和操作,z這篇文章主要為大家介紹了python如何利用DPKT實(shí)現(xiàn)分析數(shù)據(jù)包,有需要的可以參考下2023-10-10使用Django搭建網(wǎng)站實(shí)現(xiàn)商品分頁功能
這篇文章主要介紹了使用Django搭建網(wǎng)站實(shí)現(xiàn)商品分頁功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05