python爬虫之xpath的基本使用详解


Posted in Python onApril 18, 2018

一、简介

XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 都构建于 XPath 表达之上。 

二、安装

pip3 install lxml

三、使用

1、导入

from lxml import etree

2、基本使用

from lxml import etree
wb_data = """
    <div>
      <ul>
         <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>

         <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>

         <li class="item-inactive"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>

         <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>

         <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>
       </ul>
     </div>

    """
html = etree.HTML(wb_data)
print(html)
result = etree.tostring(html)
print(result.decode("utf-8"))

从下面的结果来看,我们打印机html其实就是一个python对象,etree.tostring(html)则是不全里html的基本写法,补全了缺胳膊少腿的标签。

<Element html at 0x39e58f0>
<html><body><div>
      <ul>
         <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>

         <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>

         <li class="item-inactive"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>

         <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>

         <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>

       </li></ul>
     </div>
    </body></html>

3、获取某个标签的内容(基本使用),注意,获取a标签的所有内容,a后面就不用再加正斜杠,否则报错。

写法一

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/div/ul/li/a')

print(html)

for i in html_data:

  print(i.text)

<Element html at 0x12fe4b8>

first item

second item

third item

fourth item

fifth item

写法二(直接在需要查找内容的标签后面加一个/text()就行)

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/div/ul/li/a/text()')

print(html)

for i in html_data:

  print(i) 

<Element html at 0x138e4b8>

first item

second item

third item

fourth item

fifth item

4、打开读取html文件

#使用parse打开html的文件

html = etree.parse('test.html')

html_data = html.xpath('//*')<br>#打印是一个列表,需要遍历

print(html_data)

for i in html_data:

  print(i.text)
html = etree.parse('test.html')

html_data = etree.tostring(html,pretty_print=True)

res = html_data.decode('utf-8')

print(res)

 

打印:

<div>

   <ul>

     <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>

     <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>

     <li class="item-inactive"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>

     <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>

     <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a></li>

   </ul>

</div>

5、打印指定路径下a标签的属性(可以通过遍历拿到某个属性的值,查找标签的内容)

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/div/ul/li/a/@href')

for i in html_data:

  print(i)

打印:

link1.html

link2.html

link3.html

link4.html

link5.html

6、我们知道我们使用xpath拿到得都是一个个的ElementTree对象,所以如果需要查找内容的话,还需要遍历拿到数据的列表。

查到绝对路径下a标签属性等于link2.html的内容。

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/div/ul/li/a[@href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]/text()')

print(html_data)

for i in html_data:

  print(i)

打印:

['second item']

second item

7、上面我们找到全部都是绝对路径(每一个都是从根开始查找),下面我们查找相对路径,例如,查找所有li标签下的a标签内容。

html = etree.HTML(wb_data)

html_data = html.xpath('//li/a/text()')

print(html_data)

for i in html_data:

  print(i)

打印:

['first item', 'second item', 'third item', 'fourth item', 'fifth item']

first item

second item

third item

fourth item

fifth item

8、上面我们使用绝对路径,查找了所有a标签的属性等于href属性值,利用的是/---绝对路径,下面我们使用相对路径,查找一下l相对路径下li标签下的a标签下的href属性的值,注意,a标签后面需要双//。

html = etree.HTML(wb_data)

html_data = html.xpath('//li/a//@href')

print(html_data)

for i in html_data:

  print(i)

打印:

['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']

link1.html

link2.html

link3.html

link4.html

link5.html

9、相对路径下跟绝对路径下查特定属性的方法类似,也可以说相同。

html = etree.HTML(wb_data)

html_data = html.xpath('//li/a[@href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')

print(html_data)

for i in html_data:

  print(i.text)

打印:

[<Element a at 0x216e468>]

second item

10、查找最后一个li标签里的a标签的href属性

html = etree.HTML(wb_data)

html_data = html.xpath('//li[last()]/a/text()')

print(html_data)

for i in html_data:

  print(i)

打印:

['fifth item']

fifth item

11、查找倒数第二个li标签里的a标签的href属性 

html = etree.HTML(wb_data)

html_data = html.xpath('//li[last()-1]/a/text()')

print(html_data)

for i in html_data:

  print(i)

打印:

['fourth item']

fourth item

12、如果在提取某个页面的某个标签的xpath路径的话,可以如下图:

//*[@id="kw"]

解释:使用相对路径查找所有的标签,属性id等于kw的标签。

python爬虫之xpath的基本使用详解

常用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from scrapy.selector import Selector, HtmlXPathSelector
from scrapy.http import HtmlResponse
html = """<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <ul>
      <li class="item-"><a id='i1' href="link.html" rel="external nofollow" rel="external nofollow" >first item</a></li>
      <li class="item-0"><a id='i2' href="llink.html" rel="external nofollow" >first item</a></li>
      <li class="item-1"><a href="llink2.html" rel="external nofollow" rel="external nofollow" >second item<span>vv</span></a></li>
    </ul>
    <div><a href="llink2.html" rel="external nofollow" rel="external nofollow" >second item</a></div>
  </body>
</html>
"""
response = HtmlResponse(url='http://example.com', body=html,encoding='utf-8')
# hxs = HtmlXPathSelector(response)
# print(hxs)
# hxs = Selector(response=response).xpath('//a')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[2]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[@id]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[@id="i1"]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[@href="link.html" rel="external nofollow" rel="external nofollow" ][@id="i1"]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[contains(@href, "link")]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[starts-with(@href, "link")]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]')
# print(hxs)
# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/text()').extract()
# print(hxs)
# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/@href').extract()
# print(hxs)
# hxs = Selector(response=response).xpath('/html/body/ul/li/a/@href').extract()
# print(hxs)
# hxs = Selector(response=response).xpath('//body/ul/li/a/@href').extract_first()
# print(hxs)
 
# ul_list = Selector(response=response).xpath('//body/ul/li')
# for item in ul_list:
#   v = item.xpath('./a/span')
#   # 或
#   # v = item.xpath('a/span')
#   # 或
#   # v = item.xpath('*/a/span')
#   print(v)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 实现简单的shell sed替换功能(实例讲解)
Sep 29 Python
深入浅析Python科学计算库Scipy及安装步骤
Oct 12 Python
如何运行带参数的python脚本
Nov 15 Python
python pygame实现球球大作战
Nov 25 Python
基于numpy中的expand_dims函数用法
Dec 18 Python
Pytorch 之修改Tensor部分值方式
Dec 27 Python
Python生成词云的实现代码
Jan 14 Python
利用python生成照片墙的示例代码
Apr 09 Python
Python3爬虫中Ajax的用法
Jul 10 Python
tensorflow与numpy的版本兼容性问题的解决
Jan 08 Python
Python中使用Lambda函数的5种用法
Apr 01 Python
Python面向对象之成员相关知识总结
Jun 24 Python
基于python list对象中嵌套元组使用sort时的排序方法
Apr 18 #Python
python购物车程序简单代码
Apr 18 #Python
python list元素为tuple时的排序方法
Apr 18 #Python
详谈Python中列表list,元祖tuple和numpy中的array区别
Apr 18 #Python
Python3实现购物车功能
Apr 18 #Python
Python numpy 点数组去重的实例
Apr 18 #Python
对numpy中轴与维度的理解
Apr 18 #Python
You might like
很好用的PHP数据库类
2009/05/27 PHP
php自动加载机制的深入分析
2013/06/08 PHP
php实现异步数据调用的方法
2015/12/24 PHP
Symfony2使用第三方库Upload制作图片上传实例详解
2016/02/04 PHP
PHP扩展迁移为PHP7扩展兼容性问题记录
2016/02/15 PHP
PHP中快速生成随机密码的几种方式
2017/04/17 PHP
PHP实现的链式队列结构示例
2017/09/15 PHP
关于PHP虚拟主机概念及如何选择稳定的PHP虚拟主机
2018/11/20 PHP
Jquery在IE7下无法使用 $.ajax解决方法
2009/11/11 Javascript
jQuery的强大选择器小结
2009/12/27 Javascript
JavaScript性能陷阱小结(附实例说明)
2010/12/28 Javascript
基于jQuery实现表格数据的动态添加与统计的代码
2011/01/31 Javascript
Node.js 去掉种子(torrent)文件里的邪恶信息
2015/03/27 Javascript
分享网页检测摇一摇实例代码
2016/01/14 Javascript
js实现文本上下来回滚动
2017/02/03 Javascript
用nodeJS搭建本地文件服务器的几种方法小结
2017/03/16 NodeJs
bootstrap table动态加载数据示例代码
2017/03/25 Javascript
浅谈JS封闭函数、闭包、内置对象
2017/07/18 Javascript
javascript连接mysql与php通过odbc连接任意数据库的实例
2017/12/27 Javascript
详解使用 Node.js 开发简单的脚手架工具
2018/06/08 Javascript
react-router-dom 嵌套路由的实现
2020/05/02 Javascript
微信小程序实现菜单左右联动
2020/05/19 Javascript
基于vue.js仿淘宝收货地址并设置默认地址的案例分析
2020/08/20 Javascript
详解Java中String JSONObject JSONArray List转换
2020/11/13 Javascript
[55:16]Mski vs VGJ.S Supermajor小组赛C组 BO3 第二场 6.3
2018/06/04 DOTA
Python3多线程爬虫实例讲解代码
2018/01/05 Python
Python pycharm 同时加载多个项目的方法
2019/01/17 Python
Tensorflow获取张量Tensor的具体维数实例
2020/01/19 Python
Saucony澳大利亚官网:美国跑鞋品牌,运动鞋中的劳斯莱斯
2018/05/05 全球购物
卡骆驰德国官方网站:Crocs德国
2019/03/29 全球购物
护士自荐信
2013/10/25 职场文书
啦啦队口号大全
2014/06/16 职场文书
会计求职自荐信
2014/06/20 职场文书
法院授权委托书范文
2014/08/02 职场文书
师德师风事迹材料
2014/12/20 职场文书
2015年新农村建设工作总结
2015/05/22 职场文书