爬虫-XPath

这篇讲什么

  • XPath 在 Python 里由 lxml 实现,本机环境是 Python 3.14.10 + lxml 6.1.3 + parsel 1.12.1,文里每条表达式都真跑过,输出逐字贴出。
  • 语法面按「路径 → 谓词 → 定位 → 取文本取属性 → 轴 → 运算符」过一遍,13 个轴每个都有实测结果。
  • 语言级演示跑在一份固定小 HTML 片段上;凡是真的抓页面,一律用 ssr1.scrape.center——《Python3 网络爬虫开发实战》作者搭的公开练习站,专门给爬虫练手,不校验请求头。
  • 工程面处理四个真实坑:多类名属性匹配不到、文本里的换行缩进、取不到值时的报错、防盗链的 Referer;只有懒加载和防盗链这类协议级演示还留在本机靶站。
  • 最后给一份从列表页翻到详情页的完整脚本,以及 lxml 6 / parsel 1.12 上已经失效的老写法清单和报错原文。

用哪个库

1
pip install lxml parsel

实测装完后本机版本:

x00_versions.py
1
2
3
4
5
6
7
8
import sys

import lxml.etree as ET
import parsel

print("Python %s | lxml %s | libxml2 %s | parsel %s" % (
sys.version.split()[0], ".".join(map(str, ET.LXML_VERSION[:3])),
".".join(map(str, ET.LIBXML_COMPILED_VERSION)), parsel.__version__))
1
Python 3.14.10 | lxml 6.1.3 | libxml2 2.11.9 | parsel 1.12.1
  • XPath 语言本身是 W3C 在 1999 年定下的标准,Python 里干活的是 lxml,它把 libxml2 的 XPath 引擎包了一层。

  • lxml 只实现 XPath 1.0(libxml2 2.11.9),XPath 2.0 才有的函数和运算符在这里都会报错,实测见「版本坑与老写法」。

  • 三个模块的分工:

    模块 定位 什么时候用
    lxml.etree 底层解析与查询,XML 和 HTML 都能读 要控制解析器、要改写文档、要处理 XML
    lxml.html 在 etree 之上加了 HTML 便利方法 只处理 HTML,且想用一个函数取全部文字
    parsel.Selector 在 lxml 外面再包一层,取用更方便 爬虫首选,Scrapy 内部用的就是它
  • 新手建议从 parsel 起步,理由有三条:

    • 同一个对象既支持 .xpath() 又支持 .css(),一条路走不通可以换写法。
    • 取结果只用 .get() / .getall() / .re() / .re_first(),不用自己判空取下标。
    • 它就是 Scrapy 里的 response.selector,学会直接能用在 Scrapy 上。
  • 装 parsel 会带出 cssselect(把 CSS 选择器翻译成 XPath)和 w3lib,本机实测是 cssselect 1.6.0、w3lib 2.6.0、soupsieve 4.0.1。

XML 与 HTML

  • XPath 是为 XML 设计的语言,而「XML 严格、HTML 宽松」这个差别直接决定你的表达式会不会报错。同一段残缺代码,两种解析器结局完全不同:
x01_xml_html.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from lxml import etree

broken = "<div><p>残缺<b>粗体</b></div>"
xml_doc = b'<?xml version="1.0" encoding="utf-8"?>'
xml_doc += b'<bookstore><book lang="eng"><title>iOS</title></book></bookstore>'

print("HTML 解析器 :", etree.tostring(etree.HTML(broken), encoding="unicode"))
try:
etree.fromstring(broken.encode())
except etree.XMLSyntaxError as exc:
print("XML 解析器 :", exc)
print("XML 解析器 :", etree.tostring(etree.fromstring(xml_doc), encoding="unicode"))
print("自闭合 XML :", etree.tostring(etree.fromstring(b"<a><b/></a>"), encoding="unicode"))
print("自闭合 HTML:", etree.tostring(etree.HTML("<a><b/></a>"), encoding="unicode"))
print("大写标签 :", etree.tostring(etree.HTML("<DIV><IMG SRC='a'>"), encoding="unicode"))
print("布尔属性 :", etree.tostring(etree.HTML("<input disabled>"), encoding="unicode"))
print("未知实体 :", etree.tostring(etree.HTML("<p>&unknown;</p>"), encoding="unicode"))
1
2
3
4
5
6
7
8
HTML 解析器 : <html><body><div><p>残缺<b>粗体</b></p></div></body></html>
XML 解析器 : Opening and ending tag mismatch: p line 1 and div, line 1, column 26 (<string>, line 1)
XML 解析器 : <bookstore><book lang="eng"><title>iOS</title></book></bookstore>
自闭合 XML : <a><b/></a>
自闭合 HTML: <html><body><a><b/></a></body></html>
大写标签 : <html><body><div><img src="a"/></div></body></html>
布尔属性 : <html><body><input disabled="disabled"/></body></html>
未知实体 : <html><body><p>&amp;unknown;</p></body></html>
  • 从输出能读出五条实测差别:

    • 残缺标签:HTML 解析器帮你补齐并套上 html/body,XML 解析器直接抛 XMLSyntaxError。
    • 标签大小写:HTML 解析器一律转小写,所以写 //IMG 取不到东西,要写 //img。
    • 布尔属性:HTML 里 disabled 会被补成 disabled="disabled",判属性存在要用 @disabled 而不是比字符串。
    • 未知实体:HTML 把 &unknown; 当纯文本转义掉,XML 则会直接报错。
    • 结构补全:HTML 解析后一定有 html/body 两层,所以 /html/body/div 这种绝对路径才写得通。
  • 记一句就够:抓网页永远走 HTML 解析入口,只有确认对方给的是合法 XML(RSS、SOAP 接口)才用 XML 入口。

两种入口

lxml.etree 这条线

  • etree.HTML() 吃 HTML,etree.fromstring() 吃 XML,etree.parse() 读本地文件。三者对「传 str 还是 bytes」的要求不一样:
x02_etree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from lxml import etree

xml_doc = b'<?xml version="1.0" encoding="utf-8"?><a><b>x</b></a>'

print("1 传 str 且带 XML 声明:")
try:
etree.fromstring(xml_doc.decode())
except ValueError as exc:
print(" ValueError:", exc)
print("2 传 bytes:", etree.tostring(etree.fromstring(xml_doc), encoding="unicode"))
print("3 HTML 走 etree.HTML:", etree.tostring(etree.HTML("<a><b>x</b></a>")))
print("4 默认编码转义中文:", etree.tostring(etree.HTML("<div>中文</div>")))
print("5 encoding='utf-8': ", etree.tostring(etree.HTML("<div>中文</div>"), encoding="utf-8"))
print("6 encoding='unicode':", repr(etree.tostring(etree.HTML("<div>中文</div>"),
encoding="unicode")))
try:
etree.tostring(etree.HTML("<div>中文</div>"), method="text")
except UnicodeEncodeError as exc:
print("7 method='text' 不给编码:UnicodeEncodeError:", exc)
print("8 method='text' + unicode:",
repr(etree.tostring(etree.HTML("<div>中<b>文</b>后</div>"),
method="text", encoding="unicode")))
try:
etree.parse("no-such-file.html")
except OSError as exc:
print("9 parse 找不到文件:OSError:", exc)
try:
etree.parse("broken.html")
except etree.XMLSyntaxError as exc:
print("10 parse 读残缺 HTML:XMLSyntaxError:", exc)
print("11 parse + HTMLParser:",
etree.parse("broken.html", etree.HTMLParser()).getroot().xpath("//li/text()"))
1
2
3
4
5
6
7
8
9
10
11
12
1 传 str 且带 XML 声明:
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
2 传 bytes: <a><b>x</b></a>
3 HTML 走 etree.HTML: b'<html><body><a><b>x</b></a></body></html>'
4 默认编码转义中文: b'<html><body><div>&#20013;&#25991;</div></body></html>'
5 encoding='utf-8': b'<html><body><div>\xe4\xb8\xad\xe6\x96\x87</div></body></html>'
6 encoding='unicode': '<html><body><div>中文</div></body></html>'
7 method='text' 不给编码:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
8 method='text' + unicode: '中文后'
9 parse 找不到文件:OSError: Error reading file 'no-such-file.html': failed to load external entity "no-such-file.html"
10 parse 读残缺 HTML:XMLSyntaxError: Opening and ending tag mismatch: p line 6 and body, line 7, column 8 (broken.html, line 7)
11 parse + HTMLParser: ['a', 'b']
  • 参数说清楚:etree.HTML(text, parser=None, *, base_url=None),text 可以是 str 或 bytes,parser 是 HTMLParser/XMLParser 实例,base_url 只影响相对链接。

  • 第 1 行和第 10 行是新手最常撞的两个报错:

    • 内容里有 <?xml ... encoding="..."?> 时必须传 bytes,传 str 会抛 ValueError。
    • etree.parse() 默认用 XML 解析器,读一份不规范的本地 HTML 会抛 XMLSyntaxError,正确做法是显式传 etree.HTMLParser(),实测见第 11 行。
  • etree.tostring() 默认返回 bytes,并且按 ASCII 转义非英文字符,想让中文原样出来有两条路:encoding="utf-8"(仍是 bytes)或 encoding="unicode"(返回 str)。

  • method="text" 只输出文字,不给编码时会因为默认 ASCII 而炸,实测见第 7 行。

parsel 这条线

  • 官方推荐的爬虫写法是把响应体直接交给 Selector,取结果一律用 .get() / .getall()。从这一节开始就是真页面了:示例统一用 ssr1 列表页,它服务端渲染、不校验请求头,requests.get() 裸连就能拿到带数据的 HTML。
x03_parsel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import requests

from parsel import Selector

BASE = "https://ssr1.scrape.center"
CARD = "//div[contains(@class,'el-card') and contains(@class,'item')]"

resp = requests.get(BASE + "/", timeout=20)
sel = Selector(text=resp.text)
print("01 type(sel.xpath(...)) ->", type(sel.xpath("//h2")).__name__)
print("02 type(元素) ->", type(sel.xpath("//h2")[0]).__name__)
print("03 xpath 取名称 ->", sel.xpath(CARD + "//h2/text()").getall()[:3])
print("04 css 取名称 ->", sel.css("div.item h2::text").getall()[:3])
print("05 取属性 ->", sel.xpath(CARD + "//a[@class='name']/@href").getall()[:3])
print("06 get() 只要第一个 ->", sel.xpath("//h2/text()").get())
print("07 落空 get()/getall() ->", sel.xpath("//nope").get(), sel.xpath("//nope").getall())
try:
sel.xpath("//nope")[0]
except IndexError as exc:
print("08 落空再 [0] -> IndexError:", exc)
print("09 re() 抽评分 ->", sel.xpath("//p[contains(@class,'score')]/text()").re(r"[\d.]+")[:3])
print("10 re_first() ->", sel.xpath("//p[contains(@class,'score')]/text()").re_first(r"[\d.]+"))
print("11 attrib ->", sel.xpath(CARD + "//a[@class='name']")[0].attrib)
print("12 嵌套取一张卡片 ->", sel.xpath(CARD).getall()[0][:60], "...")
card = sel.xpath(CARD)[1]
print("13 在子 Selector 上继续 ->", card.xpath(".//h2/text()").get(),
card.xpath(".//a[@class='name']/@href").get())
print("14 表达式写错 ->")
try:
sel.xpath("///").getall()
except ValueError as exc:
print(" ValueError:", exc)
print("15 css 写错 ->")
try:
sel.css("a[=]").getall()
except Exception as exc: # noqa: BLE001
print(" ", type(exc).__name__, exc)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
01 type(sel.xpath(...))   -> SelectorList
02 type(元素) -> Selector
03 xpath 取名称 -> ['霸王别姬 - Farewell My Concubine', '这个杀手不太冷 - Léon', '肖申克的救赎 - The Shawshank Redemption']
04 css 取名称 -> ['霸王别姬 - Farewell My Concubine', '这个杀手不太冷 - Léon', '肖申克的救赎 - The Shawshank Redemption']
05 取属性 -> ['/detail/1', '/detail/2', '/detail/3']
06 get() 只要第一个 -> 霸王别姬 - Farewell My Concubine
07 落空 get()/getall() -> None []
08 落空再 [0] -> IndexError: list index out of range
09 re() 抽评分 -> ['9.5', '9.5', '9.5']
10 re_first() -> 9.5
11 attrib -> {'data-v-7f856186': '', 'href': '/detail/1', 'class': 'name'}
12 嵌套取一张卡片 -> <div data-v-7f856186="" class="el-card item m-t is-hover-sha ...
13 在子 Selector 上继续 -> 这个杀手不太冷 - Léon /detail/2
14 表达式写错 ->
ValueError: XPath error: Invalid expression in ///
15 css 写错 ->
SelectorSyntaxError Expected ident or '*', got <DELIM '=' at 2>
  • Selector() 的常用参数:text= 只收 str,body= 收 bytes(encoding= 默认 utf-8),type= 可写 html/xml/json/text,不写就自动判断,base_url= 用来补全相对链接。

  • .xpath() 返回 SelectorList(一个列表),列表元素是 Selector,所以可以在它上面继续查,实测第 13 行。

  • 落空时的行为不一样,这一条能省掉很多崩溃:

    • .get() 返回 None,.getall() 返回 []。
    • [0] 直接抛 IndexError: list index out of range,见第 8 行。
    • 可能取不到的字段一律写 .get(),别写下标。
  • 表达式写错是编译期就报错,不会静默返回空列表,报错信息里带原始表达式,见第 14、15 行。

  • 开头那个 CARD 不是随手写的:@class 精确匹配在这个页面上会全军覆没,原因见「四种定位」。

路径表达式

写法 含义
/html/body/div 从根节点开始,一级一级往下走
//li 文档里任何位置的 li,不管层级
. 当前节点
.. 当前节点的父节点
@class 当前节点的 class 属性
text() 当前节点直接的文本子节点
node() 当前节点的所有子节点(元素、文本、注释都要)
* 通配符,任意元素;跟在 @ 后是任意属性
comment() 只取注释节点
  • 语言级表达式先跑在一份固定的小 HTML 上,它被当成字符串直接喂给解析器,后面「取文本与取属性」「13 个轴」「运算符」「取不到值怎么办」四节都复用它:
x04_paths.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from parsel import Selector

FRAGMENT = """<html><head><title>三国演义</title></head><body>
<div class="book" id="book-1">
<h1 class="title">三国演义</h1>
<p class="meta">作者:<span class="author">罗贯中</span> 价格:<span class="price">39.5</span></p>
<ul class="tags">
<li>历史</li>
<li>小说</li>
</ul>
<!-- 这段是给「取注释」用的 -->
<table id="stock">
<tr><th>库存</th><td>12</td></tr>
<tr><th>可借</th><td>3</td></tr>
</table>
<a class="more" href="detail/2?id=3" title="再看看">更多</a>
<p class="desc">三国演义,罗贯中。</p>
</div>
</body></html>"""

sel = Selector(text=FRAGMENT)


def show(expr, node=sel):
print("%-40s %s" % (expr, node.xpath(expr).getall()))


show("/html/body/div/h1/text()")
show("//li/text()")
show("//ul[@class='tags']/li[2]/text()")
show("//h1/@class")
show("//title/text()")
show("//comment()")
print()
node = sel.xpath("//h1[@class='title']")[0]
print("%-40s %s" % ("node.xpath('./text()')", node.xpath("./text()").getall()))
print("%-40s %s" % ("node.xpath('../@id')", node.xpath("../@id").getall()))
print("%-40s %s" % ("node.xpath('../*/@class')", node.xpath("../*/@class").getall()))
print()
show("//ul[@class='tags']/*")
show("//ul[@class='tags']/text()")
show("//div[@class='book']//@*")
show("//li/text() | //h1/text()")
print()
print("%-40s %s" % ("count(//li)", repr(sel.xpath("count(//li)").get())))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/html/body/div/h1/text()                 ['三国演义']
//li/text() ['历史', '小说']
//ul[@class='tags']/li[2]/text() ['小说']
//h1/@class ['title']
//title/text() ['三国演义']
//comment() ['<!-- 这段是给「取注释」用的 -->']

node.xpath('./text()') ['三国演义']
node.xpath('../@id') ['book-1']
node.xpath('../*/@class') ['title', 'meta', 'tags', 'more', 'desc']

//ul[@class='tags']/* ['<li>历史</li>', '<li>小说</li>']
//ul[@class='tags']/text() ['\n ', '\n ', '\n ']
//div[@class='book']//@* ['book', 'book-1', 'title', 'meta', 'author', 'price', 'tags', 'stock', 'more', 'detail/2?id=3', '再看看', 'desc']
//li/text() | //h1/text() ['三国演义', '历史', '小说']

count(//li) '2.0'
  • //title/text() 取到的是 <head> 里的网页标题,和 //h1 是两码事,别把标签名当语义。
  • //ul[@class='tags']/* 里的 * 代表任意元素,//@* 代表任意属性,两个星号位置不同含义不同。
  • text() 只拿直接文本子节点,所以 //ul[@class='tags']/text() 取到三段纯空白,里面的「历史」「小说」要经过 li 才拿得到。
  • count() 这类函数写在路径外面,返回的是字符串而不是节点;string()、normalize-space()、concat() 的完整对照放在下一节。

谓词与索引

  • 谓词就是方括号 [...],在候选节点里再筛一层。XPath 的下标从 1 开始,不是 0。
  • 先用最经典的 bookstore 那份 XML 把速查表跑一遍,再验证「第一个」的真实含义:
x15_bookstore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from parsel import Selector

XML = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="eng">Everyday Italian</title>
<price>30.00</price>
</book>
<book category="children">
<title lang="chn">Childhood</title>
<price>35.00</price>
</book>
<book category="web">
<title>XQuery Basics</title>
<price>39.95</price>
</book>
<book category="web webdb">
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
</bookstore>
"""

SHOPS = """<shops>
<shop city="hz"><book>书A</book><book>书B</book></shop>
<shop city="bj"><book>书C</book><book>书D</book></shop>
</shops>
"""

sel = Selector(text=XML, type="xml")
shops = Selector(text=SHOPS, type="xml")


def show(node, expr):
try:
found = [str(x)[:22] for x in node.xpath(expr).getall()]
except ValueError as exc:
found = str(exc)
print("%-52s %s" % (expr, found))


show(sel, "/bookstore/book[1]/title/text()")
show(sel, "/bookstore/book[last()]/title/text()")
show(sel, "/bookstore/book[last()-1]/title/text()")
show(sel, "/bookstore/book[position()<3]/title/text()")
show(sel, "//title[@lang]/text()")
show(sel, "//title[not(@lang)]/text()")
show(sel, "//title[@lang='eng']/text()")
show(sel, "//title[not(@lang='eng')]/text()")
show(sel, "name(/bookstore/*[1])")
show(sel, "/bookstore/*[1]/name()")
show(sel, "//book[price>35.00]/title/text()")
show(sel, "//book/title | //book/price")
show(sel, "//book[contains(concat(' ', @category, ' '), ' webdb ')]/title/text()")
print()
show(shops, "//book[1]/text()")
show(shops, "(/shops/shop/book)[1]/text()")
show(shops, "//shop[2]/book[1]/text()")
show(shops, "//book[2]/text()")
print()
show(sel, "//book[number(price)>30 and @category]")
show(sel, "//book[@category='web' or price>39]/title/text()")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/bookstore/book[1]/title/text()                      ['Everyday Italian']
/bookstore/book[last()]/title/text() ['Harry Potter']
/bookstore/book[last()-1]/title/text() ['XQuery Basics']
/bookstore/book[position()<3]/title/text() ['Everyday Italian', 'Childhood']
//title[@lang]/text() ['Everyday Italian', 'Childhood', 'Harry Potter']
//title[not(@lang)]/text() ['XQuery Basics']
//title[@lang='eng']/text() ['Everyday Italian', 'Harry Potter']
//title[not(@lang='eng')]/text() ['Childhood', 'XQuery Basics']
name(/bookstore/*[1]) ['book']
/bookstore/*[1]/name() XPath error: Invalid expression in /bookstore/*[1]/name()
//book[price>35.00]/title/text() ['XQuery Basics']
//book/title | //book/price ['<title lang="eng">Ever', '<price>30.00</price>', '<title lang="chn">Chil', '<price>35.00</price>', '<title>XQuery Basics</', '<price>39.95</price>', '<title lang="eng">Harr', '<price>29.99</price>']
//book[contains(concat(' ', @category, ' '), ' webdb ')]/title/text() ['Harry Potter']

//book[1]/text() ['书A', '书C']
(/shops/shop/book)[1]/text() ['书A']
//shop[2]/book[1]/text() ['书C']
//book[2]/text() ['书B', '书D']

//book[number(price)>30 and @category] ['<book category="childr', '<book category="web">\n']
//book[@category='web' or price>39]/title/text() ['XQuery Basics']
  • //book[1] 的真实含义是每个父节点下的第一个,两个 shop 各出一个(书A、书C),要「全局第一个」得先加括号 (/shops/shop/book)[1]。
  • 属性值是字符串,@category='web webdb' 必须完全相等才命中,多类名要用 contains(concat(' ', @category, ' '), ' webdb ') 这个套路。
  • 排除某值有两种写法:not(@lang='eng') 和 @lang != 'eng' 结果不同,后者会把没有 lang 属性的节点也排除掉(属性缺失时比较结果为假)。
  • name() 这类函数只能整体包住表达式,写成一步路径 /bookstore/*[1]/name() 会报 Invalid expression。

四种定位

  • 属性定位、层级定位、索引定位、模糊匹配,这四类占了爬虫场景的九成。全部在 ssr1 列表页上跑,第一个坑就从那里来:
x05_locate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import requests

from cssselect import GenericTranslator
from parsel import Selector

BASE = "https://ssr1.scrape.center"
CARD = "//div[contains(@class,'el-card') and contains(@class,'item')]"

resp = requests.get(BASE + "/", timeout=20)
sel = Selector(text=resp.text)


def show(expr):
items = sel.xpath(expr).getall()
if items and items[0].lstrip().startswith("<"):
print("%-60s 命中 %d 个元素" % (expr, len(items)))
else:
print("%-60s 命中 %d 条,前 3 条 %s" % (expr, len(items), items[:3]))


print("-- 属性定位,先记一个坑")
show("//div[@class='el-card item']")
show(CARD)
show("//div[contains(concat(' ', normalize-space(@class), ' '), ' item ')]")
show("//div[@class='el-card item m-t is-hover-shadow']")
print("%-60s 命中 %d 个元素" % ("css: div.item", len(sel.css("div.item"))))
print("cssselect 把 div.item 编译成:", GenericTranslator().css_to_xpath("div.item"))
print("-- 属性定位(正常)")
show("//a[@class='name']")
show("//li[@class='number']")
show("//p[@class='score m-t-md m-b-n-sm']")
show("//button[contains(@class,'category')]/span/text()")
print("-- 层级定位")
show(CARD + "//a[@class='name']/@href")
show("//div[contains(@class,'el-card')]/div//h2/text()")
print("-- 索引定位(从 1 开始,0 静默空)")
show("(//div[contains(@class,'el-card')])[1]//h2/text()")
show("(//div[contains(@class,'el-card')])[0]//h2/text()")
show("//li[@class='number'][2]/a/@href")
show("//li[@class='number'][last()]/a/@href")
print("-- 谓词串联")
show("//li[@class='number'][a/@href]")
print("-- 模糊匹配")
show("//h2[contains(text(),'杀手')]/text()")
show("//a[starts-with(@href,'/page')]/@href")
print("-- 按文本反查")
show("//a[text()='2']/@href")
show("//h2[text()='这个杀手不太冷 - Léon']/ancestor::a[1]/@href")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-- 属性定位,先记一个坑
//div[@class='el-card item'] 命中 0 条,前 3 条 []
//div[contains(@class,'el-card') and contains(@class,'item')] 命中 10 个元素
//div[contains(concat(' ', normalize-space(@class), ' '), ' item ')] 命中 10 个元素
//div[@class='el-card item m-t is-hover-shadow'] 命中 10 个元素
css: div.item 命中 10 个元素
cssselect 把 div.item 编译成: descendant-or-self::div[@class and contains(@class, 'item') and contains(concat(' ', normalize-space(@class), ' '), ' item ')]
-- 属性定位(正常)
//a[@class='name'] 命中 10 个元素
//li[@class='number'] 命中 10 个元素
//p[@class='score m-t-md m-b-n-sm'] 命中 10 个元素
//button[contains(@class,'category')]/span/text() 命中 28 条,前 3 条 ['剧情', '爱情', '剧情']
-- 层级定位
//div[contains(@class,'el-card') and contains(@class,'item')]//a[@class='name']/@href 命中 10 条,前 3 条 ['/detail/1', '/detail/2', '/detail/3']
//div[contains(@class,'el-card')]/div//h2/text() 命中 10 条,前 3 条 ['霸王别姬 - Farewell My Concubine', '这个杀手不太冷 - Léon', '肖申克的救赎 - The Shawshank Redemption']
-- 索引定位(从 1 开始,0 静默空)
(//div[contains(@class,'el-card')])[1]//h2/text() 命中 1 条,前 3 条 ['霸王别姬 - Farewell My Concubine']
(//div[contains(@class,'el-card')])[0]//h2/text() 命中 0 条,前 3 条 []
//li[@class='number'][2]/a/@href 命中 1 条,前 3 条 ['/page/3']
//li[@class='number'][last()]/a/@href 命中 1 条,前 3 条 ['/page/11']
-- 谓词串联
//li[@class='number'][a/@href] 命中 10 个元素
-- 模糊匹配
//h2[contains(text(),'杀手')]/text() 命中 1 条,前 3 条 ['这个杀手不太冷 - Léon']
//a[starts-with(@href,'/page')]/@href 命中 12 条,前 3 条 ['/page/1', '/page/2', '/page/3']
-- 按文本反查
//a[text()='2']/@href 命中 1 条,前 3 条 ['/page/2']
//h2[text()='这个杀手不太冷 - Léon']/ancestor::a[1]/@href 命中 1 条,前 3 条 ['/detail/2']
  • 这个坑值得单独说:卡片真实 class 是 el-card item m-t is-hover-shadow,@class='el-card item' 是完全相等比较,命中 0;要么 contains 把两个词都写进谓词,要么用 contains(concat(' ', normalize-space(@class), ' '), ' item ') 这个按词切分的套路,才命中 10。
  • CSS 的 div.item 不受影响,因为 cssselect 把类选择器编译成带 contains(concat(' ', ...)) 的词匹配(编译结果就是上面打印的那行),这层翻译替你避开了坑。
  • 把整串类名写全也能命中 10,但站点哪天给卡片再加一个类名就又不行了,实战别写死全串。
  • 同一页的第二现场:当前页那个 li 的 class 是 number active,//li[@class='number'] 恰好漏掉它,所以 [last()] 落在 /page/11 上,翻过头会 500,见「实战」。
  • (//div[contains(@class,'el-card')])[0] 不报错,只是永远取不到东西(下标从 1 开始),这种静默失败比抛异常更难查;要「全局第一个」得像 [1] 那行一样先加括号。
  • 两个谓词可以串起来写://li[@class='number'][a/@href] 等价于在谓词里用 and。
  • 拿不准一段文字在哪个标签里时,用 //a[text()='2'] 这种按文本反查比猜 class 稳,配 ancestor:: 还能从标题回找到它所在的链接。

取文本与取属性

  • 同样是「把这段文字拿出来」,text()、//text()、string()、normalize-space() 四种写法拿到的东西不一样,继续跑在「路径表达式」那份 FRAGMENT 上:
x06_text.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from parsel import Selector

FRAGMENT = """<html><head><title>三国演义</title></head><body>
<div class="book" id="book-1">
<h1 class="title">三国演义</h1>
<p class="meta">作者:<span class="author">罗贯中</span> 价格:<span class="price">39.5</span></p>
<ul class="tags">
<li>历史</li>
<li>小说</li>
</ul>
<!-- 这段是给「取注释」用的 -->
<table id="stock">
<tr><th>库存</th><td>12</td></tr>
<tr><th>可借</th><td>3</td></tr>
</table>
<a class="more" href="detail/2?id=3" title="再看看">更多</a>
<p class="desc">三国演义,罗贯中。</p>
</div>
</body></html>"""


sel = Selector(text=FRAGMENT) # 同一份片段,见「路径表达式」那节


def show(expr):
try:
result = sel.xpath(expr).getall()
except ValueError as exc:
result = "%s: %s" % (type(exc).__name__, exc)
print("%-58s %s" % (expr, result if isinstance(result, str) else repr(result)))


show("//span[@class='author']/text()")
show("//p[@class='meta']/text()")
show("//p[@class='meta']//text()")
show("string(//p[@class='meta'])")
show("normalize-space(//p[@class='meta'])")
show("//p[@class='meta']/string(.)")
show("//li/normalize-space()")
show("concat(//span[@class='author']/text(), '|', //span[@class='price']/text())")
show("//a/@href")
show("//ul[@class='tags']/node()")
print()
node = sel.xpath("//span[@class='author']")[0]
print("子 Selector 上继续取:", node.xpath("string(.)").get(), "|", node.xpath("../@class").getall())
1
2
3
4
5
6
7
8
9
10
11
12
//span[@class='author']/text()                             ['罗贯中']
//p[@class='meta']/text() ['作者:', '\u3000价格:']
//p[@class='meta']//text() ['作者:', '罗贯中', '\u3000价格:', '39.5']
string(//p[@class='meta']) ['作者:罗贯中\u3000价格:39.5']
normalize-space(//p[@class='meta']) ['作者:罗贯中\u3000价格:39.5']
//p[@class='meta']/string(.) ValueError: XPath error: Invalid expression in //p[@class='meta']/string(.)
//li/normalize-space() ValueError: XPath error: Invalid expression in //li/normalize-space()
concat(//span[@class='author']/text(), '|', //span[@class='price']/text()) ['罗贯中|39.5']
//a/@href ['detail/2?id=3']
//ul[@class='tags']/node() ['\n ', '<li>历史</li>', '\n ', '<li>小说</li>', '\n ']

子 Selector 上继续取: 罗贯中 | ['meta']
  • 四种取法怎么选:

    • text() 返回若干个文本节点,夹在标签之间的文字会被切段,实测 //p[@class='meta']/text() 只拿到 ['作者:', '\u3000价格:'],两个 span 里的内容都不在里面。
    • //text() 取子树里所有文本节点,能拿全,但仍是分段列表。
    • string(...) 把整棵子树的文字拼成一个字符串,实测得到 作者:罗贯中 价格:39.5,缺点是两段之间不会自动加空格。
    • normalize-space(...) 在 string() 之上再做空白归一,实测对这段没变化,因为中间那个是全角空格。
  • string() 和 normalize-space() 是函数,只能整体包住表达式,写成一步路径 //li/normalize-space() 直接报 Invalid expression。

  • 想自己控制分隔符,就先取到节点的 Selector 再写 string(.),或用 concat() 手拼,实测拼出 罗贯中|39.5。

  • //a/@href 拿到的是属性值的列表而不是元素,detail/2?id=3 这种相对地址要自己用 urllib.parse.urljoin 补全。

  • node() 把空白文本、元素、注释一起给你,实测 //ul[@class='tags']/node() 是「空白-元素-空白-元素-空白」交错。

13 个轴一次跑完

  • 轴(Axes)用来表达「相对当前节点的位置关系」,语法是 轴名::节点测试,这是 XPath 比 CSS 强的根本原因。
  • 还是「路径表达式」那份小片段:p.meta 里嵌着 span.author 和 span.price,后面跟着 ul.tags 和 table#stock,最适合练轴。
轴名 结果
ancestor 当前节点的所有先辈(父、祖父……)
ancestor-or-self 所有先辈加上自己
attribute 当前节点的所有属性,等价于 @
child 所有直接子节点,等价于 /
descendant 所有后代(子、孙……)
descendant-or-self 所有后代加上自己,等价于 //
following 当前节点结束标签之后的所有节点
following-sibling 之后的同级兄弟节点
namespace 当前节点的命名空间节点
parent 父节点,等价于 ..
preceding 文档里当前节点之前、且不是它祖先的所有节点
preceding-sibling 之前的同级兄弟节点
self 当前节点本身
x07_axes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from parsel import Selector

FRAGMENT = """<html><head><title>三国演义</title></head><body>
<div class="book" id="book-1">
<h1 class="title">三国演义</h1>
<p class="meta">作者:<span class="author">罗贯中</span> 价格:<span class="price">39.5</span></p>
<ul class="tags">
<li>历史</li>
<li>小说</li>
</ul>
<!-- 这段是给「取注释」用的 -->
<table id="stock">
<tr><th>库存</th><td>12</td></tr>
<tr><th>可借</th><td>3</td></tr>
</table>
<a class="more" href="detail/2?id=3" title="再看看">更多</a>
<p class="desc">三国演义,罗贯中。</p>
</div>
</body></html>"""


sel = Selector(text=FRAGMENT) # 同一份片段,见「路径表达式」那节
CTX = "//span[@class='price']"
AXES = ["ancestor", "ancestor-or-self", "attribute", "child", "descendant",
"descendant-or-self", "following", "following-sibling", "namespace",
"parent", "preceding", "preceding-sibling", "self"]


def name_of(item):
tag = getattr(item.root, "tag", None)
return tag if isinstance(tag, str) else type(item.root).__name__


for axis in AXES:
expr = "%s/%s::*" % (CTX, axis)
print("%-42s %s" % (axis + "::*", [name_of(x) for x in sel.xpath(expr)]))

print()
print("%-42s %s" % ("ancestor::p", sel.xpath(CTX + "/ancestor::p/@class").getall()))
print("%-42s %s" % ("child::text()", sel.xpath("//ul[@class='tags']/child::text()").getall()))
print("%-42s %s" % ("descendant::li/text()",
sel.xpath("//div[@class='book']/descendant::li/text()").getall()))
print("%-42s %s" % ("following::table[1]/@id",
sel.xpath("//ul[@class='tags']/following::table[1]/@id").getall()))
print("%-42s %s" % ("preceding-sibling::th/text()",
sel.xpath("//td/preceding-sibling::th/text()").getall()))
print("%-42s %s" % ("self::span", sel.xpath(CTX + "/self::span/@class").getall()))
print("%-42s %s" % ("self::h1 名字不对就空", sel.xpath(CTX + "/self::h1").getall()))
print("%-42s %s" % ("parent:: 与 .. 等价", (sel.xpath(CTX + "/parent::p/@class").getall(),
sel.xpath(CTX + "/../@class").getall())))
try:
sel.xpath(CTX + "/parant::*").getall()
except ValueError as exc:
print("%-42s %s" % ("轴名写错 parant::*", exc))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ancestor::*                                ['html', 'body', 'div', 'p']
ancestor-or-self::* ['html', 'body', 'div', 'p', 'span']
attribute::* ['str']
child::* []
descendant::* []
descendant-or-self::* ['span']
following::* ['ul', 'li', 'li', 'table', 'tr', 'th', 'td', 'tr', 'th', 'td', 'a', 'p']
following-sibling::* []
namespace::* ['tuple']
parent::* ['p']
preceding::* ['head', 'title', 'h1', 'span']
preceding-sibling::* ['span']
self::* ['span']

ancestor::p ['meta']
child::text() ['\n ', '\n ', '\n ']
descendant::li/text() ['历史', '小说']
following::table[1]/@id ['stock']
preceding-sibling::th/text() ['库存', '可借']
self::span ['price']
self::h1 名字不对就空 []
parent:: 与 .. 等价 (['meta'], ['meta'])
轴名写错 parant::* XPath error: Invalid expression in //span[@class='price']/parant::*
  • 上半段里的空列表都是正确结果:span.price 没有子元素,所以 child::*、descendant::* 为空;它是 p.meta 的最后一个孩子,所以 following-sibling::* 为空。

  • attribute::* 和 namespace::* 取到的不是元素,打印出来的类型是 str 和 tuple,别去读它们的 .tag。

  • 三个最常用来救场的写法:

    • //td/preceding-sibling::th:表格行里从数据格反查表头,实测拿到 ['库存', '可借']。
    • //ul[@class='tags']/following::table[1]:跳过中间节点找后面第一个表格,实测拿到 ['stock']。
    • //h1/parent::div/@id:先定位小标签再回父层取属性,和 ../@id 完全等价。
  • preceding 和 preceding-sibling 的差别在范围:前者是整个文档里当前节点之前、且不是它祖先的节点,实测按文档顺序列出 head、title、h1、span,后者只看同一层。

  • 轴名拼错属于语法错误,直接抛 XPath error: Invalid expression,不会静默返回空列表。

运算符

  • 算术、比较、布尔这几组全在下面这份小片段上逐条实测(FRAGMENT 和 sel 承接「路径表达式」,and/or/not() 的谓词写法在「谓词与索引」已经测过,不重复):
x08_ops.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from parsel import Selector

FRAGMENT = """<html><head><title>三国演义</title></head><body>
<div class="book" id="book-1">
<h1 class="title">三国演义</h1>
<p class="meta">作者:<span class="author">罗贯中</span> 价格:<span class="price">39.5</span></p>
<ul class="tags">
<li>历史</li>
<li>小说</li>
</ul>
<!-- 这段是给「取注释」用的 -->
<table id="stock">
<tr><th>库存</th><td>12</td></tr>
<tr><th>可借</th><td>3</td></tr>
</table>
<a class="more" href="detail/2?id=3" title="再看看">更多</a>
<p class="desc">三国演义,罗贯中。</p>
</div>
</body></html>"""


sel = Selector(text=FRAGMENT) # 同一份片段

def show(expr):
try:
print("%-40s %s" % (expr, sel.xpath(expr).getall()))
except ValueError as exc:
print("%-40s %s" % (expr, exc))


show("//h1 | //h1")
show("//h1/text() | //title/text()")
show("count(//li)+count(//p)")
show("count(//*)-count(//p)")
show("count(//li)*2")
show("count(//li) div 2")
show("count(//*) mod 3")
show("1+2*3")
show("(1+2)*3")
show("10 mod 4 div 2")
show("10 mod (4 div 2)")
show("false() and false() or true()")
show("'10' = '10'")
show("'10' < '9'")
show("'a' < 'b'")
show("1 < 2")
show("number('10') > number('9')")
show("//h1 + 1")
show("'3' + 2")
show("//span[@class='price'][text() > 39]")
show("//span[@class='price'][text() <= 39]")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//h1 | //h1                              ['<h1 class="title">三国演义</h1>']
//h1/text() | //title/text() ['三国演义', '三国演义']
count(//li)+count(//p) ['4.0']
count(//*)-count(//p) ['19.0']
count(//li)*2 ['4.0']
count(//li) div 2 ['1.0']
count(//*) mod 3 ['0.0']
1+2*3 ['7.0']
(1+2)*3 ['9.0']
10 mod 4 div 2 ['1.0']
10 mod (4 div 2) ['0.0']
false() and false() or true() ['1']
'10' = '10' ['1']
'10' < '9' ['0']
'a' < 'b' ['0']
1 < 2 ['1']
number('10') > number('9') ['1']
//h1 + 1 ['nan']
'3' + 2 ['5.0']
//span[@class='price'][text() > 39] ['<span class="price">39.5</span>']
//span[@class='price'][text() <= 39] []
  • | 去重看节点不看内容://h1 | //h1 只有一个,而 //h1/text() | //title/text() 是两条不同节点,即使文字一样都会保留。
  • 算术运算符一律先转数字:'3' + 2 得 5.0 而不是拼接;节点集参与算术时取它的文字转数字,h1 的文字是中文,转出来就是 nan。
  • 谓词里的比较同理://span[@class='price'][text() > 39] 把文本 '39.5' 转成数再比才命中,写 text() <= 39 就是空。
  • 字符串比大小不可靠:实测 'a' < 'b' 为假,libxml2 会把操作数转成数字再比,非数字串转出来是 nan,任何比较都假。要排序请拿回 Python 里比。
  • 优先级实测:*、div、mod 高于 +、-,所以 1+2*3 得 7;mod 和 div 同级、从左往右算,10 mod 4 div 2 得 1;and 高于 or。
  • XPath 2.0 的字母运算符(ne、le、ge)在 lxml 里用不了,报错原文见「版本坑与老写法」。

XPath 还是 CSS

  • 同一个需求两种写法,先在 ssr1 列表页上逐条对照,再看各自做不到什么:
x14_css.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import time

import requests

from parsel import Selector

BASE = "https://ssr1.scrape.center"

resp = requests.get(BASE + "/", timeout=20)
sel = Selector(text=resp.text)

PAIRS = [
("class 串写全", "//div[@class='el-card item']", "div.item"),
("按 class", "//div[contains(@class,'el-card') and contains(@class,'item')]", "div.item"),
("属性值前缀", "//a[starts-with(@href,'/detail')]", "a[href^='/detail']"),
("属性值包含", "//a[contains(@href,'/page/')]", "a[href*='/page/']"),
("属性值后缀", "//a[substring(@href, string-length(@href))='2']", "a[href$='2']"),
("取文本", "//p[contains(@class,'score')]/text()", "p.score::text"),
("取属性", "//a/@href", "a::attr(href)"),
("后代", "//div[contains(@class,'el-card')]//h2", "div.item h2"),
("直接子", "//div[contains(@class,'el-card')]/div", "div.el-card > div"),
("第 2 个", "//ul[@class='el-pager']/li[2]", "ul.el-pager > li:nth-child(2)"),
("最后一个", "//ul[@class='el-pager']/li[last()]", "ul.el-pager > li:last-child"),
]
print("== 两种写法逐条对照(前 24 个字符一致就算相同)")
for name, xpath, css in PAIRS:
x = [str(i)[:24] for i in sel.xpath(xpath).getall()]
c = [str(i)[:24] for i in sel.css(css).getall()]
print("%-10s %-56s %-30s %s %d 条" % (name, xpath, css, "一致" if x == c else "不同", len(x)))

print()
print("== 各自做不到的")
print("XPath 按文本反查 :", sel.xpath("//a[text()='2']/@href").getall())
print("XPath 兄弟轴 :", sel.xpath("//li[contains(@class,'active')]/following-sibling::li[1]/a/@href").getall())
print("CSS :has 扩展 :", len(sel.css("div.item:has(h2)")), "条")
try:
sel.css("div < h2").getall()
except Exception as exc: # noqa: BLE001
print("CSS 找父节点 ->", type(exc).__name__, exc)
try:
sel.xpath("//div item").getall()
except ValueError as exc:
print("XPath 用空格当后代选择器 ->", exc)

print()
print("== 速度(同一份 %d 字符的列表页,各跑 2000 次)" % len(resp.text))
start = time.perf_counter()
for _ in range(2000):
sel.xpath("//div[contains(@class,'el-card') and contains(@class,'item')]//h2/text()").getall()
cost_x = time.perf_counter() - start
start = time.perf_counter()
for _ in range(2000):
sel.css("div.item h2::text").getall()
cost_c = time.perf_counter() - start
print("xpath %.3fs | css %.3fs | xpath/css = %.2f" % (cost_x, cost_c, cost_x / cost_c))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
== 两种写法逐条对照(前 24 个字符一致就算相同)
class 串写全 //div[@class='el-card item'] div.item 不同 0 条
按 class //div[contains(@class,'el-card') and contains(@class,'item')] div.item 一致 10 条
属性值前缀 //a[starts-with(@href,'/detail')] a[href^='/detail'] 一致 20 条
属性值包含 //a[contains(@href,'/page/')] a[href*='/page/'] 一致 12 条
属性值后缀 //a[substring(@href, string-length(@href))='2'] a[href$='2'] 一致 4 条
取文本 //p[contains(@class,'score')]/text() p.score::text 一致 10 条
取属性 //a/@href a::attr(href) 一致 33 条
后代 //div[contains(@class,'el-card')]//h2 div.item h2 一致 10 条
直接子 //div[contains(@class,'el-card')]/div div.el-card > div 不同 20 条
第 2 个 //ul[@class='el-pager']/li[2] ul.el-pager > li:nth-child(2) 一致 1 条
最后一个 //ul[@class='el-pager']/li[last()] ul.el-pager > li:last-child 一致 1 条

== 各自做不到的
XPath 按文本反查 : ['/page/2']
XPath 兄弟轴 : ['/page/2']
CSS :has 扩展 : 10 条
CSS 找父节点 -> SelectorSyntaxError Expected selector, got <DELIM '<' at 4>
XPath 用空格当后代选择器 -> XPath error: Invalid expression in //div item

== 速度(同一份 41316 字符的列表页,各跑 2000 次)
xpath 0.205s | css 0.227s | xpath/css = 0.90
  • 上表 11 条里 9 条「一致」,常规筛选两者等价;两条「不同」都值得记住。
  • 第一条是「四种定位」那个 class 全等坑的再现:XPath 的 @class= 比整串,CSS 的 .item 按词切,同一需求一边 0 条一边 10 条。
  • 第二条反过来:contains(@class,'el-card') 是子串匹配,把 el-card__body 也算成含 el-card,命中 20 个;CSS 的 .el-card 按完整词元只命中真正的 el-card,要对齐就得用 concat 词切分写法。
  • CSS 的文本能力靠 soupsieve 扩展::contains() 是它的私有语法,写进 Scrapy 或换到浏览器里都不认;:has() 实测能用(10 条),但别指望跨环境行为一致。
  • CSS 真正做不到的是向上和向后:div < h2 这种父选择器实测抛 SelectorSyntaxError,兄弟轴也没有对应写法,这类需求只能 XPath。
  • XPath 反过来也有坑:CSS 里 li a 是后代选择器,XPath 里必须写 //li//a,写空格直接报 Invalid expression。
  • 速度实测两者几乎一样(4 万多字符的页面各跑 2000 次,差 0.02 秒),所以按表达力选,不按性能选。

取不到值怎么办

  • 老教程里常见一句「XPath 取不到值会报错」,实测到底谁报错、报什么,一次说清。FRAGMENT 见「路径表达式」:
x09_empty.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from lxml import etree

from parsel import Selector

FRAGMENT = """<html><head><title>三国演义</title></head><body>
<div class="book" id="book-1">
<h1 class="title">三国演义</h1>
<p class="meta">作者:<span class="author">罗贯中</span> 价格:<span class="price">39.5</span></p>
<ul class="tags"><li>历史</li><li>小说</li></ul>
<table id="stock"><tr><th>库存</th><td>12</td></tr><tr><th>可借</th><td>3</td></tr></table>
<a class="more" href="detail/2?id=3" title="再看看">更多</a>
<p class="desc">三国演义,罗贯中。</p>
</div></body></html>"""

tree = etree.fromstring(FRAGMENT)
row = tree.xpath("//table[@id='stock']/tr")[0]
print("1 xpath 命中 :", row.xpath("./th/text()"))
print("2 xpath 落空 :", row.xpath("./td[@class='nope']/div/a/i/text()"))
try:
row.xpath("./td[@class='nope']/div/a/i/text()")[0]
except IndexError as exc:
print("3 落空后硬取 [0] : IndexError:", exc)
print("4 findtext 带 default:", row.findtext("./td[@class='nope']/div/a/i", default="缺省"))
print("5 findtext 命中 :", tree.findtext(".//h1", default="缺省"))
print("6 find 落空返回 :", tree.find(".//a[@id='nope']"))
try:
tree.find(".//a[@id='nope']").get("href", "缺省")
except AttributeError as exc:
print("7 None 上再 .get() : AttributeError:", exc)
safe = tree.find(".//a[@id='nope']")
print("8 先判空再取 :", safe.get("href", "缺省") if safe is not None else "缺省")
print("9 findtext 里写 text():")
try:
tree.findtext(".//h1/text()")
except KeyError as exc:
print(" KeyError:", exc)
print("10 findtext 里写 or :")
try:
tree.findall(".//li[@class='a' or @class='b']")
except SyntaxError as exc:
print(" SyntaxError:", exc)

sel = Selector(text=FRAGMENT)
print("11 parsel get() 落空 :", repr(sel.xpath("//nope/text()").get()))
print("12 parsel getall()落空:", sel.xpath("//nope/text()").getall())
print("13 or 兜底 :", sel.xpath("//nope/text()").get() or "缺省")
print("14 string() 兜底 :", repr(sel.xpath("string(//nope)").get()))
print("15 count() 判存在 :", sel.xpath("count(//aside)").get())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1 xpath 命中         : ['库存']
2 xpath 落空 : []
3 落空后硬取 [0] : IndexError: list index out of range
4 findtext 带 default: 缺省
5 findtext 命中 : 三国演义
6 find 落空返回 : None
7 None 上再 .get() : AttributeError: 'NoneType' object has no attribute 'get'
8 先判空再取 : 缺省
9 findtext 里写 text():
KeyError: '()'
10 findtext 里写 or :
SyntaxError: invalid predicate
11 parsel get() 落空 : None
12 parsel getall()落空: []
13 or 兜底 : 缺省
14 string() 兜底 : ''
15 count() 判存在 : 0.0
  • 结论是:.xpath() 取不到只会返回空列表,报错的是你自己紧接着写的 [0],见第 3 行。

  • 三种兜底写法:

    • parsel 用 .get(),落空是 None,再配 or "默认值",见第 11、13 行。
    • 要一个空字符串就用 string(...),落空是 '',见第 14 行。
    • 只想判断存不存在就用 count(...),不存在返回 0.0,见第 15 行。
  • findtext(path, default=...) 确实能兜底,但它是 ElementTree 那一套,走的是 ElementPath 而不是 XPath:写 text() 报 KeyError: '()',写 or 报 invalid predicate,实测见第 9、10 行。

  • 所以规则很简单:.xpath() 配 get(),find() 系列配 ElementPath,两套语法不要混用。

换行与空白

  • 页面源码里的缩进和换行都会变成真实的文本节点,这是 XPath 取不到值的第一大原因。先看 ssr1 列表页的评分:
x10_newline.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import requests

from parsel import Selector

BASE = "https://ssr1.scrape.center"
CARD = "//div[contains(@class,'el-card') and contains(@class,'item')]"

resp = requests.get(BASE + "/", timeout=20)
sel = Selector(text=resp.text)

print("== 真实页面:评分数字前的缩进")
print("1 评分 text() 原样 :",
repr(sel.xpath(CARD + "//p[contains(@class,'score')]/text()").getall()[:2]))
print("2 string(第一张卡评分 p) :",
repr(sel.xpath("string(%s//p[contains(@class,'score')])" % CARD).get()))
print("3 normalize-space 归一 :",
repr(sel.xpath("normalize-space(%s//p[contains(@class,'score')])" % CARD).get()))
print("4 分类 div 的直接文本 :",
sel.xpath(CARD + "//div[contains(@class,'categories')]/text()").getall()[:3])
print("5 名称 text() 是干净的 :",
repr(sel.xpath(CARD + "//h2/text()").getall()[:2]))
print("6 strip 过滤法 :",
[t.strip() for t in sel.xpath(CARD + "//p[contains(@class,'score')]/text()").getall()
if t.strip()][:3])
print("7 re() 直接抽数字 :",
sel.xpath(CARD + "//p[contains(@class,'score')]/text()").re(r"[\d.]+")[:3])
print("8 精确匹配 text()='9.5' :", sel.xpath("//p[text()='9.5']").getall())
print("9 normalize-space(text()):",
sel.xpath("//p[normalize-space(text())='9.5']/text()").getall()[:2])

print()
print("== 属性值里带换行")
raw = ('<div class="card">\n'
' <span class="name">\n 罗贯中\n </span>\n'
' <a href="/detail/1"\n title="第一行\n第二行">三国演义</a>\n'
'</div>')
frag = Selector(text=raw)
print("10 span/text() :", frag.xpath("//span[@class='name']/text()").getall())
print("11 //span[text()='罗贯中'] :", frag.xpath("//span[text()='罗贯中']").getall())
print("12 normalize-space(text())=", frag.xpath(
"//span[normalize-space(text())='罗贯中']/text()").getall())
print("13 @title 实际值 :", repr(frag.xpath("//a/@title").get()))
print("14 用带 \\n 的字面量匹配 :", len(frag.xpath("//a[@title='第一行\n第二行']")))
print("15 用带空格的字符串匹配 :", len(frag.xpath("//a[@title='第一行 第二行']")))
print("16 normalize-space(@title):", repr(frag.xpath("normalize-space(//a/@title)").get()))
print("17 contains(@title,'第一行'):", frag.xpath("//a[contains(@title,'第一行')]/text()").getall())
print("18 strip() 之后 :", repr(frag.xpath("//span/text()").get().strip()))
print("19 全角空格 strip() 也吃 :", repr(" 罗贯中 ".strip()))
print("20 normalize-space 不吃全角:",
Selector(text="<p> x y </p>").xpath("normalize-space(//p)").getall())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
== 真实页面:评分数字前的缩进
1 评分 text() 原样 : ['\n 9.5', '\n 9.5']
2 string(第一张卡评分 p) : '\n 9.5'
3 normalize-space 归一 : '9.5'
4 分类 div 的直接文本 : ['\n \n ', '\n \n ', '\n \n ']
5 名称 text() 是干净的 : ['霸王别姬 - Farewell My Concubine', '这个杀手不太冷 - Léon']
6 strip 过滤法 : ['9.5', '9.5', '9.5']
7 re() 直接抽数字 : ['9.5', '9.5', '9.5']
8 精确匹配 text()='9.5' : []
9 normalize-space(text()): ['\n 9.5', '\n 9.5']

== 属性值里带换行
10 span/text() : ['\n 罗贯中\n ']
11 //span[text()='罗贯中'] : []
12 normalize-space(text())= ['\n 罗贯中\n ']
13 @title 实际值 : '第一行\n第二行'
14 用带 \n 的字面量匹配 : 1
15 用带空格的字符串匹配 : 0
16 normalize-space(@title): '第一行 第二行'
17 contains(@title,'第一行'): ['三国演义']
18 strip() 之后 : '罗贯中'
19 全角空格 strip() 也吃 : '罗贯中'
20 normalize-space 不吃全角: ['\u3000x\u3000y\u3000']
  • 实测四条结论:

    • 评分的文本节点是 '\n 9.5',数字前面带着源码里的换行和一整排缩进。
    • string(...) 会把换行原样带出来,normalize-space(...) 把整段压成一行 '9.5',多个空白压成一个空格且去掉首尾。
    • 文本匹配会被空白害死://p[text()='9.5'] 命中 0 条,谓词里写 normalize-space(text())='9.5' 才命中,但取出的文本仍要再清洗。
    • Python 侧最省事的写法是 [t.strip() for t in ... if t.strip()],parsel 也可以直接 .re(r"[\d.]+") 一次筛掉空白段。
  • 名称的 h2 文本干净、评分的 p 文本脏:空白在不在文本节点里取决于源码排版,没法靠猜,取回来先清洗是本能。

  • 属性值里的换行更阴险:实测 lxml 不会把 title="第一行\n第二行" 里的换行改成空格,取出来仍是原样;用带空格的字符串去匹配命中 0 条,得写 contains(@title,'第一行') 或先 normalize-space(@title)。

  • normalize-space() 只处理半角空白,实测全角空格 \u3000 原样保留,而 Python 的 str.strip() 会把它吃掉,两者不等价。

  • 存盘再读回:带换行的字符串别再用 str(list) 存加 eval() 读,eval 会把文件内容当代码执行,一律换成 json.dump / json.load,换行的转义和还原由 JSON 自己负责。

懒加载与下载图片

  • 懒加载页面的 src 是空的,真实地址藏在 data-src,XPath 取属性正好对付这种「属性名换了」的情况。
  • 这一段留在本机靶站:scrape.center 不校验 Referer(实测带不带都 200),懒加载与防盗链这两种「服务端挑毛病」的行为只有自己能搭才复现得出来。靶站的图片还带 Referer 防盗链,正好一起验证:
x11_lazy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import urllib.error
import urllib.parse
import urllib.request

from parsel import Selector

BASE = "http://127.0.0.1:8010"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/156.0"}
DIRNAME = "imgs"


def open_url(path, referer=None):
"""请求靶站的一个路径,可选带 Referer。"""
headers = dict(HEADERS)
if referer:
headers["Referer"] = referer
req = urllib.request.Request(BASE + path, headers=headers)
return urllib.request.urlopen(req, timeout=10)


req = urllib.request.Request(BASE + "/lazy", headers=HEADERS)
with urllib.request.urlopen(req, timeout=10) as resp:
lazy = Selector(body=resp.read())

print("1 //img/@src :", lazy.xpath("//img/@src").getall())
print("2 //img/@data-src :", lazy.xpath("//img/@data-src").getall())
print("3 src 为空的才要 :", lazy.xpath("//img[@src='']/@data-src").getall())
print("4 img 的全部属性名 :", [sorted(s.attrib) for s in lazy.xpath("//img")])

try:
open_url("/img/1.png")
except urllib.error.HTTPError as exc:
print("5 不带 Referer : HTTPError: HTTP Error %d: %s" % (exc.code, exc.reason))
try:
urllib.request.urlretrieve(BASE + "/img/1.png", os.path.join(DIRNAME, "raw.png"))
except urllib.error.HTTPError as exc:
print("6 urlretrieve : HTTPError: HTTP Error %d: %s" % (exc.code, exc.reason))
with open_url("/img/1.png", BASE + "/list") as resp:
print("7 带 Referer : %d 字节,状态 %d" % (len(resp.read()), resp.status))

os.makedirs(DIRNAME, exist_ok=True)
for src in lazy.xpath("//img[@src='']/@data-src").getall():
url = urllib.parse.urljoin(BASE, src)
with open_url(urllib.parse.urlparse(url).path, BASE + "/lazy") as resp:
data = resp.read()
filepath = os.path.join(DIRNAME, os.path.basename(url))
with open(filepath, "wb") as fp:
fp.write(data)
print("8 存 %s -> %s %d 字节" % (src, filepath, os.path.getsize(filepath)))
print("9 目录内容 :", sorted(os.listdir(DIRNAME)))
1
2
3
4
5
6
7
8
9
10
11
1 //img/@src        : ['', '', '']
2 //img/@data-src : ['/img/1.png', '/img/2.png', '/img/3.png']
3 src 为空的才要 : ['/img/1.png', '/img/2.png', '/img/3.png']
4 img 的全部属性名 : [['alt', 'data-src', 'src'], ['alt', 'data-src', 'src'], ['alt', 'data-src', 'src']]
5 不带 Referer : HTTPError: HTTP Error 403: Forbidden
6 urlretrieve : HTTPError: HTTP Error 403: Forbidden
7 带 Referer : 162 字节,状态 200
8 存 /img/1.png -> imgs\1.png 162 字节
8 存 /img/2.png -> imgs\2.png 165 字节
8 存 /img/3.png -> imgs\3.png 165 字节
9 目录内容 : ['1.png', '2.png', '3.png']
  • 实测三件事:

    • //img/@src 拿到三个空字符串,//img/@data-src 才是真地址,//img[@src='']/@data-src 一步筛出懒加载图。
    • 不带 Referer 请求图片是 HTTP Error 403: Forbidden,带上来源页 http://127.0.0.1:8010/list 就是 200、162 字节。
    • urllib.request.urlretrieve() 不能带请求头,所以面对防盗链必然 403,要自己用 Request + urlopen。
  • 落盘的规范写法里三处要注意:os.makedirs(DIRNAME, exist_ok=True) 避免重复建目录报错;
    os.path.basename(url) 从 /img/1.png 取文件名;urllib.parse.urljoin() 把相对地址补成绝对地址。

  • 图片是二进制,一定要 open(path, "wb"),写成文本模式会直接损坏文件。

  • 真站点的懒加载属性名五花八门,先 Selector(...).css("img").attrib 把属性名列出来看一眼,比猜 data-original、data-src2 快得多。

浏览器里验证 XPath

  • 写 XPath 最痛的是不知道表达式对不对,先在浏览器里验好再抄进 Python,打开 https://ssr1.scrape.center/ 就能拿下面的表达式练。

  • 关于 XPath Helper 这类插件,要按现状说:它是一个 Manifest V2 扩展,而 Chrome 从 2025 年中的 138 版起陆续停止加载 MV2 扩展,老版 XPath Helper 在今天的 Chrome 里已经跑不起来了;商店里还能搜到同名或同类的 MV3 扩展,但维护状态变化很快,装之前先看商店页面的更新日期。

  • 不装任何插件也能完成同样的事,DevTools 里有两条路:

    • 右键元素 -> Copy -> Copy XPath,直接拿到绝对路径。
    • 在 Elements 面板选中元素后到 Console 里用 $0 当上下文,配合 document.evaluate 验表达式。
xpath_in_devtools.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 在 DevTools 的 Console 里跑,$0 是 Elements 面板当前选中的节点
const found = document.evaluate(
"//div[contains(@class,'el-card') and contains(@class,'item')]//h2",
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null,
);

console.log("类型常量:", found.resultType, "命中:", found.snapshotLength);
for (let i = 0; i < found.snapshotLength; i++) {
console.log(i, found.snapshotItem(i).textContent);
}

// 只要第一个节点:FIRST_ORDERED_NODE_TYPE
const one = document.evaluate("//a[@class='name']", document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(one.singleNodeValue.href);

// 要布尔值/数字/字符串,直接换类型常量
console.log(document.evaluate("count(//p[contains(@class,'score')])", document, null,
XPathResult.NUMBER_TYPE, null).numberValue);
  • document.evaluate(expression, contextNode, namespaceResolver, resultType, result) 五个参数:

    • contextNode:上下文节点,整篇文档就传 document,在某节点下面找就传它并配相对路径。
    • namespaceResolver:HTML 页面传 null 就够,查带命名空间的 XML 才要传函数。
    • resultType:返回类型常量,见下表,传 0(ANY_TYPE)让引擎自己决定。
XPathResult 常量 值 取结果的方式
ANY_TYPE 0 由表达式决定,可能是下面任意一种
NUMBER_TYPE 1 .numberValue
STRING_TYPE 2 .stringValue
BOOLEAN_TYPE 3 .booleanValue
UNORDERED_NODE_ITERATOR_TYPE 4 iterateNext() 循环,改文档会失效
ORDERED_NODE_ITERATOR_TYPE 5 同上,但保证文档顺序
UNORDERED_NODE_SNAPSHOT_TYPE 6 .snapshotLength + snapshotItem(i)
ORDERED_NODE_SNAPSHOT_TYPE 7 同上且有序,日常最常用
ANY_UNORDERED_NODE_TYPE 8 .singleNodeValue,任取一个
FIRST_ORDERED_NODE_TYPE 9 .singleNodeValue,文档里第一个
  • 浏览器里的 document.evaluate 同样只实现 XPath 1.0,所以这篇里学到的函数集合(没有 ends-with、没有 matches)在这里一模一样。
  • 一个常见落差:DevTools 里 Copy XPath 给你的是绝对路径,页面结构一改就失效,抄进脚本前建议手工改成 //div[@class='...']//... 这种带锚点的相对写法。

实战:电影站翻页

  • 把前面的东西串起来:列表页抓「名称/评分/详情链接」,翻到 /page/2 验证分页,再进详情页取地区时长、上映日期、导演和演员数量,全程 XPath。
x12_ssr1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import requests

from parsel import Selector

BASE = "https://ssr1.scrape.center"
CARD = "//div[contains(@class,'el-card') and contains(@class,'item')]"


def select(path):
"""请求一个路径,把响应体交给 parsel 解析成 Selector。"""
resp = requests.get(BASE + path, timeout=20)
resp.raise_for_status()
return Selector(text=resp.text)


def parse_list(page):
"""抓一页列表,返回 (行列表, 页脚总数)。"""
sel = select("/page/%d" % page)
rows = []
for card in sel.xpath(CARD):
rows.append({
"名称": card.xpath("./descendant::h2/text()").get(),
"评分": card.xpath("normalize-space(./descendant::p[contains(@class, 'score')])").get(),
"链接": card.xpath("./descendant::a[@class='name']/@href").get(),
})
total = sel.xpath("normalize-space(//span[contains(@class, 'el-pagination__total')])").get()
return rows, total


def parse_detail(href):
"""进详情页取地区时长、上映日期、导演和演员数量。"""
sel = select(href)
infos = sel.xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' info ')]")
return {
"片名": sel.xpath("normalize-space(//h2)").get(),
"地区时长": infos[0].xpath("normalize-space(.)").get(),
"上映日期": infos[1].xpath("normalize-space(.)").get(),
"导演": sel.xpath("//div[contains(@class,'director')]"
"//p[contains(@class,'name')]/text()").get(),
"演员数": len(sel.xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' actor ')]")),
}


def main():
rows, total = parse_list(1)
print("第 1 页抓到 %d 条,页脚显示:%s" % (len(rows), total))
for row in rows[:3]:
print(" %s | %s | %s" % (row["名称"], row["评分"], row["链接"]))

print()
rows2, _ = parse_list(2)
print("第 2 页抓到 %d 条,前 3 条:" % len(rows2))
for row in rows2[:3]:
print(" %s | %s | %s" % (row["名称"], row["评分"], row["链接"]))

print()
for href in [rows[0]["链接"], rows2[0]["链接"]]:
info = parse_detail(href)
print("%s -> %s | %s | %s | 导演:%s | 演员:%d 个" % (
href, info["片名"], info["地区时长"], info["上映日期"],
info["导演"], info["演员数"]))

print()
print("页码带尾斜杠试试 /page/2/:", end="")
try:
select("/page/2/")
except requests.HTTPError as exc:
print(exc)
print("照着页码条翻到 /page/11:", end="")
try:
select("/page/11")
except requests.HTTPError as exc:
print(exc)


if __name__ == "__main__":
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
第 1 页抓到 10 条,页脚显示:共 104 条
霸王别姬 - Farewell My Concubine | 9.5 | /detail/1
这个杀手不太冷 - Léon | 9.5 | /detail/2
肖申克的救赎 - The Shawshank Redemption | 9.5 | /detail/3

第 2 页抓到 10 条,前 3 条:
V字仇杀队 - V for Vendetta | 8.9 | /detail/11
少年派的奇幻漂流 - Life of Pi | 8.9 | /detail/12
美丽心灵 - A Beautiful Mind | 8.8 | /detail/13

/detail/1 -> 霸王别姬 - Farewell My Concubine | 中国内地、中国香港 / 171 分钟 | 1993-07-26 上映 | 导演:陈凯歌 | 演员:30 个
/detail/11 -> V字仇杀队 - V for Vendetta | 美国、英国、德国 / 132 分钟 | 2005-12-11 上映 | 导演:詹姆斯·麦克特格 | 演员:96 个

页码带尾斜杠试试 /page/2/:404 Client Error: Not Found for url: https://ssr1.scrape.center/page/2/
照着页码条翻到 /page/11:500 Server Error: Internal Error for url: https://ssr1.scrape.center/page/11
  • 三个实测坑:

    • 分页 URL 不带尾斜杠:/page/2 是 200,/page/2/ 是 404;页码条列到了 /page/11,但翻到第 11 页实测 500 Server Error,列表实际最多翻到第 10 页。
    • 详情页 id 不连续:页脚写「共 104 条」,id 范围却是 1 到 108,别按 id 递增遍历详情页,跟着卡片里的链接走。
    • 评分文本节点带换行缩进,normalize-space 一步洗净,别直接比字符串,见「换行与空白」。
  • 外层先按卡片切块、块内一律用 ./descendant:: 这类相对路径,这是 XPath 抓列表最不容易串行的写法。

  • 导演卡片嵌在 div.directors 里,contains(@class,'director') 两层都会命中;取单个用 .get() 不受影响,要取全量就得回到 concat 词切分写法。

版本坑与老写法

  • 下面是 lxml 6.1.3 与 parsel 1.12.1 上的逐条实测,报错原文一律照抄:
x13_version.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import sys

import lxml
import parsel
from lxml import etree
from lxml import html as lxml_html
from parsel import Selector

print("Python", sys.version.split()[0], "| lxml", lxml.__version__,
"| libxml2", ".".join(map(str, etree.LIBXML_VERSION)), "| parsel", parsel.__version__)

frag = "<div>中<b>文</b></div>"
plain = etree.HTML(frag)
doc = lxml_html.fromstring(frag)


def boom(label, func):
try:
value = func()
except Exception as exc: # noqa: BLE001
print("%-38s %s: %s" % (label, type(exc).__name__, exc))
else:
print("%-38s OK -> %r" % (label, value))


print()
print("== lxml.etree")
print("1 etree.HTML() 的类型 :", type(plain).__name__)
print("2 lxml.html.fromstring() 的类型 :", type(doc).__name__)
boom("3 etree 元素 .text_content()", lambda: plain.text_content())
print("4 lxml.html 元素 .text_content():", repr(doc.text_content()))
print("5 替代:tostring(method='text') :",
repr(etree.tostring(plain, method="text", encoding="unicode")))
print("6 替代:itertext() :", repr("".join(plain.itertext())))
boom("7 etree.HTML(text, encoding=)", lambda: etree.HTML(frag, encoding="utf-8"))
print("8 etree.HTML 签名 :", __import__("inspect").signature(etree.HTML))
boom("9 Element('x:a') 手写前缀", lambda: etree.Element("x:a"))
print("10 Element('{URI}a') :",
etree.tostring(etree.Element("{http://ex}a")))
print("11 getchildren/iterancestors :",
[c.tag for c in doc.getchildren()], [e.tag for e in doc.iterancestors()])

print()
print("== parsel")
sel = Selector(text="<a href='x'>t</a>")
boom("12 sel.css_first()", lambda: sel.css_first("a::text"))
boom("13 sel.xpath_first()", lambda: sel.xpath("//a").xpath_first("./@href"))
boom("14 Selector(selector=sel)", lambda: Selector(selector=sel))
boom("15 Selector(text=bytes)", lambda: Selector(text=b"<a/>"))
print("16 Selector(body=bytes) :", Selector(body=b"<a>t</a>").xpath("//a/text()").get())
boom("17 sel.root() 当方法调", lambda: sel.root())
print("18 sel.root 现在是属性 :", type(sel.root).__name__)
print("19 extract()/extract_first() 仍在 :",
sel.xpath("//a/text()").extract(), sel.xpath("//a/text()").extract_first())
xml_sel = Selector(text='<r xmlns:m="http://x"><m:t>v</m:t></r>', type="xml")
boom("20 XML 默认命名空间不注册", lambda: xml_sel.xpath("//m:t/text()").getall())
print("21 namespaces= 传字典 :", Selector(
text='<r xmlns:m="http://x"><m:t>v</m:t></r>', type="xml",
namespaces={"m": "http://x"}).xpath("//m:t/text()").getall())
print("22 remove_namespaces() 的返回值 :", repr(xml_sel.remove_namespaces()))
print("23 去完之后 //t/text() :", xml_sel.xpath("//t/text()").getall())

print()
print("== XPath 版本(lxml 只实现 XPath 1.0)")
page = Selector(text="<ul><li id='a'>x</li><li id='ab'>y</li></ul>")
boom("24 ends-with()", lambda: page.xpath("//li[ends-with(@id,'a')]").getall())
boom("25 matches()", lambda: page.xpath("//li[matches(@id,'a')]").getall())
boom("26 2.0 的 ne 运算符", lambda: page.xpath("//li[@id ne 'a']").getall())
print("27 1.0 里用 substring 代替 :",
page.xpath("//li[substring(@id, string-length(@id))='a']/text()").getall())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Python 3.14.10 | lxml 6.1.3 | libxml2 2.11.9 | parsel 1.12.1

== lxml.etree
1 etree.HTML() 的类型 : _Element
2 lxml.html.fromstring() 的类型 : HtmlElement
3 etree 元素 .text_content() AttributeError: 'lxml.etree._Element' object has no attribute 'text_content'
4 lxml.html 元素 .text_content(): '中文'
5 替代:tostring(method='text') : '中文'
6 替代:itertext() : '中文'
7 etree.HTML(text, encoding=) TypeError: HTML() got an unexpected keyword argument 'encoding'
8 etree.HTML 签名 : (text, parser=None, *, base_url=None)
9 Element('x:a') 手写前缀 ValueError: Invalid tag name 'x:a'
10 Element('{URI}a') : b'<ns0:a xmlns:ns0="http://ex"/>'
11 getchildren/iterancestors : ['b'] ['body', 'html']

== parsel
12 sel.css_first() AttributeError: 'Selector' object has no attribute 'css_first'
13 sel.xpath_first() AttributeError: 'SelectorList' object has no attribute 'xpath_first'
14 Selector(selector=sel) TypeError: Selector.__init__() got an unexpected keyword argument 'selector'
15 Selector(text=bytes) TypeError: text argument should be of type str, got <class 'bytes'>
16 Selector(body=bytes) : t
17 sel.root() 当方法调 TypeError: 'HtmlElement' object is not callable
18 sel.root 现在是属性 : HtmlElement
19 extract()/extract_first() 仍在 : ['t'] t
20 XML 默认命名空间不注册 ValueError: XPath error: Undefined namespace prefix in //m:t/text()
21 namespaces= 传字典 : ['v']
22 remove_namespaces() 的返回值 : None
23 去完之后 //t/text() : ['v']

== XPath 版本(lxml 只实现 XPath 1.0)
24 ends-with() ValueError: XPath error: Unregistered function in //li[ends-with(@id,'a')]
25 matches() ValueError: XPath error: Unregistered function in //li[matches(@id,'a')]
26 2.0 的 ne 运算符 ValueError: XPath error: Invalid predicate in //li[@id ne 'a']
27 1.0 里用 substring 代替 : ['x']
  • 判定成「已经不能用」的写法:

    老写法 现在的结果 替代
    etree.HTML(text, encoding="utf-8") TypeError 不认这个参数 自己 text.encode(),或传 HTMLParser(encoding="utf-8")
    element.text_content() etree._Element 上没有这个方法 lxml.html.fromstring() 再用,或 "".join(el.itertext())
    sel.css_first() / sel.xpath_first() AttributeError,parsel 1.12 已移除 .css(...).get() / .xpath(...).get()
    Selector(selector=sel) TypeError,参数已移除 取下标后直接链式调用
    sel.root() TypeError,root 改成了属性 sel.root
    ends-with() / matches() / ne XPath 2.0 才有,报 Unregistered function 或 Invalid predicate substring + string-length、!=
  • text_content() 这条最容易踩:同样的代码,导入 lxml.html 解析出来的元素有它,etree.HTML() 解析出来的没有,实测第 1 到 4 行。

  • 带 XML 声明的内容必须传 bytes、method="text" 必须给编码,这两条在「两种入口」已经实测过,这里不再重复。

  • 仍在服役的老 API:getchildren()、iterancestors()、itersiblings()、getroottree().getpath()、.extract() / .extract_first(),实测都没报错,但新代码建议用 list(el)、轴、getall() 这些更标准的写法。

  • 命名空间两件事:XML 里用前缀必须先注册(Selector(..., namespaces={"m": "http://x"})),否则报 Undefined namespace prefix;remove_namespaces() 是原地生效、返回 None,别链式调用。

  • 传变量别拼字符串:sel.xpath("//li[@data-id=$bid]", bid="3") 由 XPath 自己处理引号,实测把带单引号的恶意串当普通文本处理;直接拼进表达式则会报 Invalid predicate。

参考

本文结束 感谢您的阅读
正在加载今日诗词....