python - 从格式不同的字段中提取数据的最佳 XPath 实践
问题描述
我正在使用 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)
这返回了: 健康 健康医生 健康医生
这是不正确的。这是谷歌浏览器中的截图:谷歌 浏览器中的 Xpath 工具以及有问题的 html
使用 Python 和 Xpath 或其他选项抓取这些数据的最佳方法是什么?谢谢你。
解决方案
在花了几个小时谷歌搜索然后在上面写了这篇文章之后,我突然想到了:旧代码:
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li")
以及返回漂亮文本列表的新代码:
Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
stuff = Services_Product[0].xpath("//li/text()")
在末尾添加“/ text()”修复它。
推荐阅读
- machine-learning - AttributeError:模块“火炬”没有属性“swapaxes”
- java - 在 ListView 中使用 Auto scoll 在 Android 中显示空白行
- actionscript-3 - As3 const 是否在编译或运行时初始化?
- bash - 如何在 Mac 中重命名重复的 .jpg 文件名
- excel - PutInClipboard 方法的结果不一致
- html - 如何在悬停时显示全文,但在使用 CSS 延迟一段时间后?
- javascript - 平面列表不显示在其他组件中
- java - 发送后删除文件android studio
- mongodb - 为什么我们在 Mongo 中需要一个带有复合索引的附加 LIMIT 阶段
- pine-script - 尝试调试此源代码,遇到一些简单的语法错误