欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python數(shù)據(jù)抓取3種方法總結

 更新時間:2021年02月07日 12:16:01   作者:呵呵樣  
這篇文章主要給大家介紹了關于python數(shù)據(jù)抓取的3種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

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

  • 正則表達式(re庫)
  • BeautifulSoup(bs4)
  • lxml

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

from get_html import download

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

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

1.正則表達式

from get_html import download
import re

url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'
page_content = download(url)
country = re.findall('class="h2dabiaoti">(.*?)</h2>', 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':'h2dabiaoti'}).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)#可進行xpath解析
country_select = selector.xpath('//*[@id="main_content"]/h2') #返回列表
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='')

運行結果:

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

僅供參考。

總結

到此這篇關于python數(shù)據(jù)抓取3種方法的文章就介紹到這了,更多相關python數(shù)據(jù)抓取內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論