Python爬虫——Xpath和lxml

栏目: Python · 发布时间: 7年前

内容简介:Xpath,全称

Xpath,全称 XML Path Language ,及XML路径语言,是一门在XML文档中查找信息的语言,最初是用来搜寻XML文档的,但是它同样适用于HTML文档的搜索。

1.2 常用规则

  • 获取文本

    表达式 描述
    a/text() 获取 a 下的文本
    a//text() 获取 a 下所有元素的文本
    //a[text()='下一页'] 获取文本为下一页的 a 元素
  • 获取属性

    表达式 描述
    nodename 选取此节点的所有子节点
    / 从当前节点选取直接子节点
    // 从当前节点选取子孙节点
    . 选取当前节点
    .. 选取当前节点的父节点
    @ 选取属性
    * 匹配任何元素节点
    @* 匹配任何属性节点
    node() 匹配任何类型的节点

1.3示例

Python爬虫——Xpath和lxml
路径表达式 结果
/bookstore/book[1] (注意下标从1开始) 选取属于 bookstore 子元素的第一个book元素
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素
/bookstore/book[position()<3] 选取属于 bookstore 子元素的 最前面两个 book 元素
//title[@lang] 选取所有拥有名为 lang 的属性的title元素
//title[@lang='eng'] 选取所有 lang 属性为 eng 的 title 元素
/bookstore/book[price>35.00] 选取 bookstore 元素下所有 book 元素,它们的 price 元素值大于 35.00
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且 price 元素的值大于35.00
/bookstore/* 选取 bookstore 的所有子元素
//* 选取文档中的所有元素
//node()/meta[]/@* 选取 html 下面任意节点的 meta 节点的所有属性
//title[@*] 选取所有带有属性的 title 元素
//book/title | // book/price 选取 book 元素的所有 title 和 price 元素
//title | //price 选取文档中的所有 title 和 price 元素
//bookstore/book/title | //price 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素

2. lxml的使用

2.1 使用注意点

  • lxml 能够修正 HTML 代码,但是可能会改错了,解决方法:

    • 使用 etree.tostring 观察修改之后的html的样子,根据修改之后的html字符串写xpath
  • 提取页面数据的思路

    • 先分组,取到一个包含分组标签的列表
    • 遍历,取其中每一组进行数据的提取,不会造成数据的对应错乱
  • lxml 能够接受bytes和str的字符串

2.2 简单示例

from lxml import etree

text = ''' <div> <ul> 
            <li class="item-1"><a href="link1.html">first item</a></li> 
            <li class="item-1"><a href="link2.html">second item</a></li> 
            <li class="item-inactive"><a href="link3.html">third item</a></li> 
            <li class="item-1"><a href="link4.html">fourth item</a></li> 
            <li class="item-0"><a href="link5.html">fifth item</a> 
            </ul> </div> '''

html = etree.HTML(text)

print(html) # <Element html at 0x1f1007c9d08>
print(etree.tostring(html).decode())

# 获取 class 为 item-1 li 下的 a 的 href
ret1 = html.xpath('//li[@class="item-1"]/a/@href')
print(ret1)

# 获取 class 为 item-1 li 下的文本
ret2 = html.xpath("//li[@class='item-1']/a/text()")
print(ret2)

# 把 url 和 文本组成字典
# 如果其中一个获取失败或者没有数据,则url 和 title 就不是原来对应的结果
for i in ret1:
    item = {}
    item['url'] = i
    item['title'] = ret2[ret1.index(i)]
    print(item)

# 改进
ret3 = html.xpath('//li[@class="item-1"]')
for i in ret3:
    item = {}
    item['url'] = i.xpath('./a/@href')[0] if len(i.xpath('./a/@href')) else None  # ./a/@href 表示当前节点下的
    item['title'] = i.xpath('./a/text()')[0] if len(i.xpath('./a/text()')) else None
    print(item)
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Illuminated (Part 2)

Algorithms Illuminated (Part 2)

Tim Roughgarden / Soundlikeyourself Publishing, LLC / 2018-8-5 / USD 17.99

Algorithms are the heart and soul of computer science. Their applications range from network routing and computational genomics to public-key cryptography and machine learning. Studying algorithms can......一起来看看 《Algorithms Illuminated (Part 2)》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具