這篇文章給大家分享的是有關(guān)python中如何實(shí)現(xiàn)數(shù)據(jù)抓取的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)是一家專業(yè)提供澤州企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)、成都h5網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為澤州眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。
三種數(shù)據(jù)抓取的方法
正則表達(dá)式(re庫(kù))
BeautifulSoup(bs4)
lxml
*利用之前構(gòu)建的下載網(wǎng)頁(yè)函數(shù),獲取目標(biāo)網(wǎng)頁(yè)的html,我們以https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/為例,獲取html。

from get_html import download url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'page_content = download(url)
*假設(shè)我們需要爬取該網(wǎng)頁(yè)中的國(guó)家名稱和概況,我們依次使用這三種數(shù)據(jù)抓取的方法實(shí)現(xiàn)數(shù)據(jù)抓取。
1.正則表達(dá)式
from get_html import downloadimport re
url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'page_content = download(url)country = re.findall('class="h3dabiaoti">(.*?)</h3>', page_content) #注意返回的是listsurvey_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 downloadfrom bs4 import BeautifulSoup
url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'html = download(url)#創(chuàng)建 beautifulsoup 對(duì)象soup = BeautifulSoup(html,"html.parser")#搜索country = soup.find(attrs={'class':'h3dabiaoti'}).text
survey_info = soup.find(attrs={'id':'wzneirong'}).textprint(country,survey_info)3.lxml
from get_html import downloadfrom 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寫網(wǎng)絡(luò)爬蟲》中對(duì)三種方法的性能對(duì)比,如下圖:
僅供參考。
感謝各位的閱讀!關(guān)于“python中如何實(shí)現(xiàn)數(shù)據(jù)抓取”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
分享名稱:python中如何實(shí)現(xiàn)數(shù)據(jù)抓取
URL網(wǎng)址:http://www.yijiale78.com/article22/pcshjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、外貿(mào)網(wǎng)站建設(shè)、微信公眾號(hào)、定制網(wǎng)站、搜索引擎優(yōu)化、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)