极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

介绍python 数据抓取三种方法

极客小将2021-02-20-
简介免费学习推荐:python视频教程三种数据抓取的方法正则表达式(re库)BeautifulSoup(bs4)lxml*利用之前构建的下载网页函数,获取目标网页的html,我们以https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/为例,获取html。fromge
u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

免费学习推荐:python视频教程u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

三种数据抓取的方法u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

正则表达式(re库)BeautifulSoup(bs4)lxml

*利用之前构建的下载网页函数,获取目标网页的html,我们以https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/为例,获取html。u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

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

*假设我们需要爬取该网页中的国家名称和概况,我们依次使用这三种数据抓取的方法实现数据抓取。
1.正则表达式u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

from get_html import downloadimport re url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'page_content = download(url)country = re.findall('class="h2dabiaoti">(.*?)</h2>', 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)u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

from get_html import downloadfrom bs4 import BeautifulSoup url = 'https://guojiadiqu.bmcx.com/AFG__guojiayudiqu/'html = download(url)#创建 beautifulsoup 对象soup = BeautifulSoup(html,"html.parser")#搜索country = soup.find(attrs={'class':'h2dabiaoti'}).text survey_info = soup.find(attrs={'id':'wzneirong'}).textprint(country,survey_info)

3.lxmlu9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

from get_html import downloadfrom 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写网络爬虫》中对三种方法的性能对比,如下图:

仅供参考。u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

相关免费学习推荐:python教程(视频)u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

以上就是介绍python 数据抓取三种方法的详细内容,更多请关注少儿编程网其它相关文章!u9d少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

预约试听课

已有385人预约都是免费的,你也试试吧...