1 在Python中使用XPath

方法一:

# -*- coding: utf-8 -*-
from lxml import etree
html = uthis is a html 内容
sel = etree.HTML(html)

方法二:

from scrapy.selector import Selector
html = uthis is a html 内容
sel = Selector(text=body)

2 XPath基本语义

样例文本

"""
<html>
<head>
<base href=http://example.com/ />
<title>Example website</title>
</head>
<body>
<div id="url">
<a href="https://www.baidu.com" title="baidu">BaiDu</a>
<a href="https://www.zhihu.com" title="zhihu">ZhiHu</a>
</div>
</body>
</html>
"""

基本语义1

//定位节点,不考虑节点的位置
/一层一层往下,按照顺序依次查找

示例

>>> sel.xpath(/html/head/title/text()).extract()
>>> sel.xpath(//title/text()).extract()
[uExample website]

基本语义2

/text():当前节点下的文本内容
/@x:当前节点下属性x的属性值

示例

>>> sel.xpath(//base/@href).extract()
[uExample Domain]
>>> sel.xpath(//*[@id="url"]/a/@title).extract() # //*表示任意节点
>>> sel.xpath(//div[@id="url"]/a/@title).extract() # 等价表示
[ubaidu, uzhihu]

3 XPath中的函数

3.1 查找特定字元串后的内容

>>> sel.xpath("substring-after(string(.), html )")
内容

讲解:

# substring-after( haystack , needle )
# haystack: 源字元串,该字元串部分内容会被返回。
# needle : 搜索的子串,其后的所有内容将被返回。

3.2 查找指定字元串开头的内容

"""<body>
<div id="test-1">string 1</div>
<div id="test-2">string 2</div>
<div id="test-3">string 3</div>
</body>
"""
>>> sel.xpath(//div[starts-with(@id,"test")]/text()).extract()
[string 1,string 2,string 3]

3.3 输出所有标签下的字元

<body>
<div id="test-1">
string 1
<span id=1>
string 2
<ul>string 3
<li>string 4</li>
</ul>
</sapn>
</div>
</body>

方法

>>> div = sel.xpath(//div[@id="test-1"])
>>> div.xpath(string(.)).extract_first().replace(
,).replace( ,)
string1string2string3string4

3.4 其他

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

输出价格大于40的书的书名

>>> sel.xpath(//bookstore/book[price>40]/title/text()).extract()
[uXQuery Kick Start]

推荐阅读:

相关文章