首页 > 解决方案 > XPath 仅适用于某些站点

问题描述

我从 lxml 的 XPath 开始。

我只是写了一些指令,但我注意到 XPath 仅适用于某些站点。

我试图解释:

如果我测试这段代码:

import requests
from lxml import html

URL = 'https://it.wikipedia.org/wiki/Pagina_principale'
page = requests.get(URL)
tree = html.fromstring(page.content)

items = tree.xpath('//div[@id="mw-navigation"]//text()')
print(items)

结果是 id="mw-navigation" 的 div 中的所有文本。

有谁知道为什么,如果我有这个 HTML 的其他网站(检查员检查):

<a id="text-search-submit">
 <span>Search</span>
</a>

并使用此代码:

import requests
from lxml import html

URL = 'https://www.sneakersnstuff.com/en/472/upcoming-releases'
page = requests.get(URL)
tree = html.fromstring(page.content)

items = tree.xpath('//a[@id="text-search-submit"]//text()')
print(items)

项目是空的?

标签: pythonxpathpython-requestslxml

解决方案


推荐阅读