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" ...
随机推荐
- js的时间展示
<script type="text/javascript">$(function() { //方法调用 showtime(); //默认加载首页 ...
- Codeforces Round #239 (Div. 1)
B. Long Path time limit per test 1 second memory limit per test 256 megabytes input standard input o ...
- 在网页上打印,js window.print
window.print默认会打印出当前页在屏幕中显示的部分,可以实现在线打印
- js的45个技巧
JavaScript是一个绝冠全球的编程语言,可用于Web开发.移动应用开发(PhoneGap.Appcelerator).服务器端开发(Node.js和Wakanda)等等.JavaScript还是 ...
- 当下较热web前端技术汇总
Web前段技术发展很快,主流技术日新月异,想想自己刚毕业那会用的asp技术,现在已经很少有主流网站在使用了.再到后来的J2EE框架,然后SpringMVC大行其道,但是最近各种js框架被广为传播,Ht ...
- [App Store Connect帮助]三、管理 App 和版本(4)创建新版本
当您准备分发 App 的新版本时,您创建的新版本使用您为原始版本创建的 App 记录.该新版本将对购买过先前版本的顾客免费可用. 各版本使用的 Apple ID(App 标识符).SKU 和套装 ID ...
- [Swift通天遁地]二、表格表单-(8)快速实现表单的输入验证
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- JVM-垃圾回收器
目录 垃圾收集器 Serial收集器 Serial Old 收集器 ParNew 收集器 Parallel Scavenge 收集器 (并行清除) /'pærəlɛl/ /'skævɪndʒ/ Par ...
- vb.net实现textbox控件输入指定位数小数方法实现。
Private Sub textbox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPres ...
- Android sensor 系统框架 (二)
连载上一篇http://www.cnblogs.com/hackfun/p/7327320.html (D) 如何加载访问.so库 在前一篇博客http://www.cnblogs.com/hackf ...