Python爬蟲實現(xiàn)爬取百度百科詞條功能實例
本文實例講述了Python爬蟲實現(xiàn)爬取百度百科詞條功能。分享給大家供大家參考,具體如下:
爬蟲是一個自動提取網(wǎng)頁的程序,它為搜索引擎從萬維網(wǎng)上下載網(wǎng)頁,是搜索引擎的重要組成。爬蟲從一個或若干初始網(wǎng)頁的URL開始,獲得初始網(wǎng)頁上的URL,在抓取網(wǎng)頁的過程中,不斷從當(dāng)前頁面上抽取新的URL放入隊列,直到滿足系統(tǒng)的一定停止條件。爬蟲的工作流程較為復(fù)雜,需要根據(jù)一定的網(wǎng)頁分析算法過濾與主題無關(guān)的鏈接,保留有用的鏈接并將其放入等待抓取的URL隊列。然后,它將根據(jù)一定的搜索策略從隊列中選擇下一步要抓取的網(wǎng)頁URL,并重復(fù)上述過程,直到達到系統(tǒng)的某一條件時停止。另外,所有被爬蟲抓取的網(wǎng)頁將會被系統(tǒng)存貯,進行一定的分析、過濾,并建立索引,以便之后的查詢和檢索。常見的爬蟲框架有Scrapy等。
自定義爬蟲程序一般包含:URL管理器、網(wǎng)頁下載器、網(wǎng)頁解析器、輸出處理器。
以下我寫了一個爬取百度百科詞條的實例。
爬蟲主程序入口
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):
# 初始值,實例化四大處理器: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() # 已爬取
# 添加一個新的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
# 從待爬取的集合中獲取一個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():
# 每個詞條中,可以有多個超鏈接
# 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" >計算機程序設(shè)計語言</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
# 每個詞條中,只有一個描述內(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>計算機程序設(shè)計語言</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正則表達式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- python 爬取百度文庫并下載(免費文章限定)
- Python實現(xiàn)的爬取百度文庫功能示例
- 用python下載百度文庫的代碼
- python 爬蟲如何實現(xiàn)百度翻譯
- 詳解用Python爬蟲獲取百度企業(yè)信用中企業(yè)基本信息
- Python爬蟲爬取百度搜索內(nèi)容代碼實例
- Python爬蟲實現(xiàn)百度翻譯功能過程詳解
- python 爬蟲百度地圖的信息界面的實現(xiàn)方法
- python爬蟲之爬取百度音樂的實現(xiàn)方法
- python爬蟲獲取百度首頁內(nèi)容教學(xué)
- Python爬蟲實現(xiàn)百度圖片自動下載
- Python爬蟲實例_利用百度地圖API批量獲取城市所有的POI點
- python實現(xiàn)百度文庫自動化爬取
相關(guān)文章
Python中的getter與setter及deleter使用示例講解
這篇文章主要介紹了Python中的getter與setter及deleter使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01
Python結(jié)合MySQL數(shù)據(jù)庫編寫簡單信息管理系統(tǒng)完整實例
最近Python課堂上布置了綜合實訓(xùn),實驗?zāi)繕?biāo)是設(shè)計一個信息管理系統(tǒng),下面這篇文章主要給大家介紹了關(guān)于Python結(jié)合MySQL數(shù)據(jù)庫編寫簡單信息管理系統(tǒng)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-06-06
在OpenCV里實現(xiàn)條碼區(qū)域識別的方法示例
這篇文章主要介紹了在OpenCV里實現(xiàn)條碼區(qū)域識別的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
keras 使用Lambda 快速新建層 添加多個參數(shù)操作
這篇文章主要介紹了keras 使用Lambda 快速新建層 添加多個參數(shù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明
這篇文章主要介紹了Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
pytorch簡單實現(xiàn)神經(jīng)網(wǎng)絡(luò)功能
這篇文章主要介紹了pytorch簡單實現(xiàn)神經(jīng)網(wǎng)絡(luò),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09
10張動圖學(xué)會python循環(huán)與遞歸問題
今天為大家整理了十張動圖GIFS,有助于認識循環(huán)、遞歸、二分檢索等概念的具體運行情況。代碼實例以Python語言編寫,非常不錯,感興趣的朋友跟隨小編一起學(xué)習(xí)吧2021-02-02

