三種數(shù)據(jù)抓取的方法
- 正則表達(dá)式(re庫)
- BeautifulSoup(bs4)
- lxml
*利用之前構(gòu)建的下載網(wǎng)頁函數(shù),獲取目標(biāo)網(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)
*假設(shè)我們需要爬取該網(wǎng)頁中的國家名稱和概況,我們依次使用這三種數(shù)據(jù)抓取的方法實現(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="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)#可進(jìn)行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='')
運行結(jié)果:
最后,引用《用python寫網(wǎng)絡(luò)爬蟲》中對三種方法的性能對比,如下圖:
僅供參考。
總結(jié)
到此這篇關(guān)于python數(shù)據(jù)抓取3種方法的文章就介紹到這了,更多相關(guān)python數(shù)據(jù)抓取內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python采用requests庫模擬登錄和抓取數(shù)據(jù)的簡單示例
- Python爬蟲抓取手機(jī)APP的傳輸數(shù)據(jù)
- 通過抓取淘寶評論為例講解Python爬取ajax動態(tài)生成的數(shù)據(jù)(經(jīng)典)
- python抓取某汽車網(wǎng)數(shù)據(jù)解析html存入excel示例
- Python實現(xiàn)并行抓取整站40萬條房價數(shù)據(jù)(可更換抓取城市)
- Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法
- 對python抓取需要登錄網(wǎng)站數(shù)據(jù)的方法詳解
- 在Python3中使用asyncio庫進(jìn)行快速數(shù)據(jù)抓取的教程
- Python抓取京東圖書評論數(shù)據(jù)
- 使用Python抓取豆瓣影評數(shù)據(jù)的方法