【发布时间】:2021-07-23 08:57:39
【问题描述】:
我使用的是 Python 3.8、XPath 和 Scrapy,但似乎一切正常。我认为我的 XPath 表达式是理所当然的。
现在我必须使用 Python 3.8、XPath 和 lxml.html 并且事情变得不那么宽容了。例如,使用这个 URL 和这个 XPath:
//dt[text()='Services/Products']/following-sibling::dd[1]
我会根据 innerhtml 的内容返回一个段落或一个列表。这就是我现在尝试提取文本的方式:
data = response.text
tree = html.fromstring(data)
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
返回这个:Services_Product[] 这是他页面的“li”元素列表,但其他时候该字段可以是以下任何一个:
<dd>some text</dd>
or
<dd><p>some text</p></dd>
or
<dd>
<ul>
<li>some text</li>
<li>some text</li>
</ul>
</dd>
or
<dd>
<ul>
<li><p>some text</p></li>
<li><p>some text</p></li>
</ul>
</dd>
在目标字段可以是多种不同事物的情况下,提取文本的最佳做法是什么?
我用这个测试代码来看看我的选择是什么:
file = open('html_01.txt', 'r')
data = file.read()
tree = html.fromstring(data)
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li")
for elem in stuff:
print(elem[0][0].text)
返回这个: 健康 健康 医生 健康 医生
这是不正确的。这是它在谷歌浏览器中的屏幕截图: The Xpath tool in google chrome along with the html in question
使用 Python 和 Xpath 或其他选项抓取这些数据的最佳方法是什么? 谢谢。
【问题讨论】:
-
最佳做法是为您提供所需的结果。