溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中數(shù)據(jù)抓取的方式有哪些

發(fā)布時(shí)間:2021-02-07 18:17:22 來源:億速云 閱讀:179 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹python中數(shù)據(jù)抓取的方式有哪些,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

三種數(shù)據(jù)抓取的方法

  • 正則表達(dá)式(re庫)

  • BeautifulSoup(bs4)

  • lxml

*利用之前構(gòu)建的下載網(wǎng)頁函數(shù),獲取目標(biāo)網(wǎng)頁的html,我們以https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/為例,獲取html。

python中數(shù)據(jù)抓取的方式有哪些

from get_html import download

url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'
page_content = download(url)

*假設(shè)我們需要爬取該網(wǎng)頁中的國家名稱和概況,我們依次使用這三種數(shù)據(jù)抓取的方法實(shí)現(xiàn)數(shù)據(jù)抓取。

1.正則表達(dá)式

from get_html import download
import re

url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'
page_content = download(url)
country = re.findall('class="h3dabiaoti">(.*?)</h3>', page_content) #注意返回的是list
survey_data = re.findall('<tr><td bgcolor="#FFFFFF" id="wzneirong">(.*?)</td></tr>', page_content)
survey_info_list = re.findall('<p>  (.*?)</p>', survey_data[0])
survey_info = ''.join(survey_info_list)
print(country[0],survey_info)

2.BeautifulSoup(bs4)

from get_html import download
from bs4 import BeautifulSoup

url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'
html = download(url)
#創(chuàng)建 beautifulsoup 對象
soup = BeautifulSoup(html,"html.parser")
#搜索
country = soup.find(attrs={'class':'h3dabiaoti'}).text
survey_info = soup.find(attrs={'id':'wzneirong'}).text
print(country,survey_info)

3.lxml

from get_html import download
from lxml import etree #解析樹

url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'
page_content = download(url)
selector = etree.HTML(page_content)#可進(jìn)行xpath解析
country_select = selector.xpath('//*[@id="main_content"]/h3') #返回列表
for country in country_select:
 print(country.text)
survey_select = selector.xpath('//*[@id="wzneirong"]/p')
for survey_content in survey_select:
 print(survey_content.text,end='')

運(yùn)行結(jié)果:

python中數(shù)據(jù)抓取的方式有哪些

最后,引用《用python寫網(wǎng)絡(luò)爬蟲》中對三種方法的性能對比,如下圖:

python中數(shù)據(jù)抓取的方式有哪些

關(guān)于python中數(shù)據(jù)抓取的方式有哪些就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI