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" ...
随机推荐
- [python基础]xml_rpc远程调控supervisor节点进程
supervisor提供的两种管理方式,supervisorctl和web其实都是通过xml_rpc来实现的. xml_rpc其实就是本地可以去调用远端的函数方法,在python中只需要引入xmlrp ...
- bzoj4082
贪心+倍增 首先如果这个问题在序列上,好像可以按右端点排序,然后从起点开始向能到的最远的地方走. 但是环上不可以,因为随即一个起点可能不是最小的. 然后神思路来了:我们先将环展开倍增,再将区间按右端点 ...
- C++ 指针 部分
基本知识:在内存中的每个字节都有一个编号,这就是“地址”,相当于旅馆中的房间号.记住,内存单元的地址和内存单元的内容是两个不同的概念. 程序在编译之后,就已经将变量名转换成变量地址,对变量值的存取都是 ...
- E20170624-ts
stateless adj. 无国家的,无国籍的; groupware 群件 cookie n. 饼干; 小甜点; 吸引人的年轻妇女; 甜面包; session n. 开会,会议; (法庭的) 开 ...
- 微信小程序图片选择,预览和删除
这里均用的是小程序原生api 废话不多说直接上栗子: <view class="addImv"> <!--这个是已经选好的图片--> <view wx ...
- Java中的管道流 PipedOutputStream和PipedInputStream
我们在学习IO流的时候可能会学字节流.字符流等,但是关于管道流的相信大部分视频或者教程都是一语带过,第一个是因为这个东西在实际开发中用的也不是很多,但是学习无止境,存在既有理.JDK中既然有个类那说明 ...
- azkaban-executor启动时出现conf/global.properties (No such file or directory)的问题解决(图文详解)
问题详情 // :: INFO [FlowRunnerManager] [Azkaban] Cleaning recently finished // :: INFO [FlowRunnerMana ...
- html5+css3杂记
H5C3个人笔记 before&after 1. 必须有content display 2. 场景:不想改变html结构:解决浮动 解决浮动: 2c d h v transition 过渡 1 ...
- 电源管理POWER_SUPPLY_PROP_CAPACITY_LEVEL
电量计节点中有capacity_level 节点,这个是反应当前电池电流高低水平的参数. 分为critical low full normal 一般是由fg的芯片来判断,通过IIC读取,具体判断可参考 ...
- highcharts 组合chart
/** *制作 复杂的组合型的 charts * *@param [options] 图表的默认配置 *@dependence jQuery.highcharts *@author wch */ fu ...