python爬虫数据解析的四种不同选择器Xpath,Beautiful Soup,pyquery,re
这里主要是做一个关于数据爬取以后的数据解析功能的整合,方便查阅,以防混淆
主要讲到的技术有Xpath,BeautifulSoup,PyQuery,re(正则)
首先举出两个作示例的代码,方便后面举例
解析之前需要先将html代码转换成相应的对象,各自的方法如下:
Xpath:
In [7]: from lxml import etree In [8]: text = etree.HTML(html)
BeautifulSoup:
In [2]: from bs4 import BeautifulSoup In [3]: soup = BeautifulSoup(html, 'lxml')
PyQuery:
In [10]: from pyquery import PyQuery as pq In [11]: doc = pq(html)
re:没有需要的对象,他是直接对字符串进行匹配的规则
示例1
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p> <p class="story">...</p>
</body>
</html>
'''
接下来我们来用不同的解析方法分析示例的HTML代码
匹配标题内容:
Xpath:
In [16]: text.xpath('//title/text()')[0]
Out[16]: "The Dormouse's story"
BeautifulSoup:
In [18]: soup.title.string
Out[18]: "The Dormouse's story"
PyQuery:
In [20]: doc('title').text()
Out[20]: "The Dormouse's story"
re:
In [11]: re.findall(r'<title>(.*?)</title></head>', html)[0]
Out[11]: "The Dormouse's story"
匹配第三个a标签的href属性:
Xpath:#推荐
In [36]: text.xpath('//a[@id="link3"]/@href')[0]
Out[36]: 'http://example.com/tillie'
BeautifulSoup:
In [27]: soup.find_all(attrs={'id':'link3'})
Out[27]: [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] In [33]: soup.find_all(attrs={'id':'link3'})[0].attrs['href']
Out[33]: 'http://example.com/tillie'
PyQuery:#推荐
In [45]: doc("#link3").attr.href
Out[45]: 'http://example.com/tillie'
re:
In [46]: re.findall(r'<a href="(.*?)" class="sister" id="link3">Tillie</a>;', html)[0]
Out[46]: 'http://example.com/tillie'
匹配P标签便是内容的全部数据:
Xpath:
In [48]: text.xpath('string(//p[@class="story"])').strip()
Out[48]: 'Once upon a time there were three little sisters; and their names were\nElsie,\nLacie and\nTillie;\nand they lived at the bottom of a well.' In [51]: ' '.join(text.xpath('string(//p[@class="story"])').split('\n'))
Out[51]: 'Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.'
BeautifulSoup:
In [89]: ' '.join(list(soup.body.stripped_strings)).replace('\n', '')
Out[89]: "The Dormouse's story Once upon a time there were three little sisters; and their names were Elsie,Lacie and Tillie; and they lived at the bottom of a well. ..."
PyQuery:
In [99]: doc('.story').text()
Out[99]: 'Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well. ...'
re:不推荐使用,过于麻烦
In [101]: re.findall(r'<p class="story">(.*?)<a href="http://example.com/elsie" class="sister" id="link1">(.*?)</a>(.*?)<a href="http://example.com/lacie" class="siste
...: r" id="link2">(.*?)</a>(.*?)<a href="http://example.com/tillie" class="sister" id="link3">(.*?)</a>;(.*?)</p>', html, re.S)[0]
Out[101]:
('Once upon a time there were three little sisters; and their names were\n',
'Elsie',
',\n',
'Lacie',
' and\n',
'Tillie',
'\nand they lived at the bottom of a well.')
示例2
html = '''
<div>
<ul>
<li class="item-0">first item</li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
<li class="item-1 active"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
</ul>
</div>
'''
匹配second item
Xpath:
In [14]: text.xpath('//li[2]/a/text()')[0]
Out[14]: 'second item'
BeautifulSoup:
In [23]: soup.find_all(attrs={'class': 'item-1'})[0].string
Out[23]: 'second item'
PyQuery:
In [34]: doc('.item-1>a')[0].text
Out[34]: 'second item'
re:
In [35]: re.findall(r'<li class="item-1"><a href="link2.html">(.*?)</a></li>', html)[0]
Out[35]: 'second item'
匹配第五个li标签的href属性:
Xpath:
In [36]: text.xpath('//li[@class="item-0"]/a/@href')[0]
Out[36]: 'link5.html'
BeautifulSoup:
In [52]: soup.find_all(attrs={'class': 'item-0'})
Out[52]:
[<li class="item-0">first item</li>,
<li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>,
<li class="item-0"><a href="link5.html">fifth item</a></li>] In [53]: soup.find_all(attrs={'class': 'item-0'})[-1].a.attrs['href']
Out[53]: 'link5.html'
PyQuery:
In [75]: [i.attr.href for i in doc('.item-0 a').items()][1]
Out[75]: 'link5.html'
re:
In [95]: re.findall(r'<li class="item-0" ><a href="(.*?)">fifth item</a></li>',html)[0]
Out[95]: 'link5.html'
示例3
<li><span class="label">房屋用途</span>普通住宅</li>
分别获取出房屋用途和普通住宅
Xpath:
In [47]: text.xpath('//li/span/text()')[0]
Out[47]: '房屋用途' In [49]: text.xpath('//li/text()')[0]
Out[49]: '普通住宅'
BeautifulSoup:
In [65]: soup.span.string
Out[65]: '房屋用途' In [69]: soup.li.contents[1] # contents 获取直接子节点
Out[69]: '普通住宅'
PyQuery:
In [70]: doc('li span').text()
Out[70]: '房屋用途' In [75]: doc('li .label')[0].tail
Out[75]: '普通住宅'
re: 略
示例4
<div class="unitPrice">
<span class="unitPriceValue">26667<i>元/平米</i></span>
</div>
分别获取26667和元/平米
Xpath:
In [81]: text.xpath('//div[@class="unitPrice"]/span/text()')[0]
Out[81]: '' In [82]: text.xpath('//div[@class="unitPrice"]/span/i/text()')[0]
Out[82]: '元/平米'
BeautifulSoup:
In [97]: [i for i in soup.find('div', class_="unitPrice").strings]
Out[97]: ['\n', '', '元/平米', '\n'] In [98]: [i for i in soup.find('div', class_="unitPrice").strings][1]
Out[98]: '' In [99]: [i for i in soup.find('div', class_="unitPrice").strings][2]
Out[99]: '元/平米'
PyQuery:
In [109]: doc('.unitPrice .unitPriceValue')[0].text
Out[109]: '' In [110]: doc('.unitPrice .unitPriceValue i')[0].text
Out[110]: '元/平米'
python爬虫数据解析的四种不同选择器Xpath,Beautiful Soup,pyquery,re的更多相关文章
- python爬虫--数据解析
数据解析 什么是数据解析及作用 概念:就是将一组数据中的局部数据进行提取 作用:来实现聚焦爬虫 数据解析的通用原理 标签定位 取文本或者属性 正则解析 正则回顾 单字符: . : 除换行以外所有字符 ...
- python爬虫数据解析之BeautifulSoup
BeautifulSoup是一个可以从HTML或者XML文件中提取数据的python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式. BeautfulSoup是python爬虫三 ...
- Python网络爬虫数据解析的三种方式
request实现数据爬取的流程: 指定url 基于request发起请求 获取响应的数据 数据解析 持久化存储 1.正则解析: 常用的正则回顾:https://www.cnblogs.com/wqz ...
- python爬虫数据解析之正则表达式
爬虫的一般分为四步,第二个步骤就是对爬取的数据进行解析. python爬虫一般使用三种解析方式,一正则表达式,二xpath,三BeautifulSoup. 这篇博客主要记录下正则表达式的使用. 正则表 ...
- [转]JSon数据解析的四种方式
转至http://blog.csdn.net/enuola/article/details/7903632 作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式. 有的js ...
- python爬虫数据解析之xpath
xpath是一门在xml文档中查找信息的语言.xpath可以用来在xml文档中对元素和属性进行遍历. 在xpath中,有7中类型的节点,元素,属性,文本,命名空间,处理指令,注释及根节点. 节点 首先 ...
- 070.Python聚焦爬虫数据解析
一 聚焦爬虫数据解析 1.1 基本介绍 聚焦爬虫的编码流程 指定url 基于requests模块发起请求 获取响应对象中的数据 数据解析 进行持久化存储 如何实现数据解析 三种数据解析方式 正则表达式 ...
- python爬虫+数据可视化项目(关注、持续更新)
python爬虫+数据可视化项目(一) 爬取目标:中国天气网(起始url:http://www.weather.com.cn/textFC/hb.shtml#) 爬取内容:全国实时温度最低的十个城市气 ...
- python 爬虫数据存入csv格式方法
python 爬虫数据存入csv格式方法 命令存储方式:scrapy crawl ju -o ju.csv 第一种方法:with open("F:/book_top250.csv" ...
随机推荐
- codility MinAbsSum
For a given array A of N integers and a sequence S of N integers from the set {−1, 1}, we define val ...
- 深入理解7816(1)---- 关于F/D和etu【转】
本文转载自:http://blog.sina.com.cn/s/blog_4df8400a0101gkss.html 深入理解7816(1)---- 关于F/D和etu 对于刚接触智能卡的工程师来说, ...
- 47. Ext.form.Field.prototype.msgTarget
转自:https://blog.csdn.net/a1542aa/article/details/24295791 ExtJS.form中msgTarget Ext表单提示方式:msgTarget:有 ...
- 05、ListActivity的使用
第一个好处:处理共同的操作,避免代码重复 假设我要写第二个界面我也是需要使用到mapView,那你都要去查找一个mapView.都要获取一个Map的一个地图. 第二个好处:代码规范(方便阅读,真实开发 ...
- selenium3 + python - 异常处理截图 screenshot
一.截图方法 1.get_screenshot_as_file(self, filename) --这个方法是获取当前window的截图,出现IOError时候返回False,截图成功返回True. ...
- HDU 5279 分治NTT 图的计数
思路: 显然每个子图内都是森林 去掉所有子图1和n都连通且每条大边都存在的情况 直接DP上 NTT优化一波 注意前两项的值.. //By SiriusRen #include <bits/std ...
- html表单代码演示
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...
- [转]linux之磁盘配额(quota)
转自:http://www.jb51.net/LINUXjishu/78446.html 磁盘配额(quota)比较常用的几个情况是: * 针对WWW server,例如:每个人的网页空间的容量限制 ...
- 大数据~说说ZooKeeper
一些概念 ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase和Kafka重要组件.它是一个为分布式应用提供一致性 ...
- [转]android 获取 imei号码
核心代码: Imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceId(); 1.加入权限 在manife ...