簡(jiǎn)單爬蟲(chóng)可以劃分為get、post格式。其中,get是單方面的獲取資源,而post存在交互,如翻譯中需要文字輸入。本文主要描述簡(jiǎn)單的get爬蟲(chóng)。
環(huán)境準(zhǔn)備
安裝第三方庫(kù)
pip install requests pip install bs4 pip install lxml
進(jìn)行爬蟲(chóng)
1.獲取網(wǎng)頁(yè)數(shù)據(jù)。
import requests from bs4 import BeautifulSoup url = "https://cn.bing.com/search?q=爬蟲(chóng)CSDN&qs=n&form=QBRE&sp=-1&pq=爬蟲(chóng)csdn&sc=5-6&sk=&cvid=0B13B88D8F444A0182A4A6C36E463179/" response = requests.get(self.url)
2.解析網(wǎng)頁(yè)數(shù)據(jù)
soup = BeautifulSoup(response.text, 'lxml')
3.選取目標(biāo)數(shù)據(jù)。此處key 依據(jù)源代碼目標(biāo)標(biāo)題的位置確定。首先進(jìn)入開(kāi)發(fā)者模式,后查看目標(biāo)在html中的位置,右擊選擇“復(fù)制selector”,見(jiàn)下圖。
key = "#b_results > li > div.b_title > h2 > a" soup.select(key)
4.清洗數(shù)據(jù)
result = {} for i, item in enumerate(data): result.update({ f'title_{i}': item.get_text(), f'url_{i}': item.get('href') }) print(result)
參考
http://www.ythuaji.com.cn/article/159801.html
總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注服務(wù)器之家的更多內(nèi)容!
原文鏈接:https://blog.csdn.net/sinat_33465240/article/details/120191249