【发布时间】:2020-05-24 18:59:10
【问题描述】:
我在尝试解析这个 lxml 时遇到了麻烦。我正在使用python语言,3.6.9。
是这样的。
<download date="22/05/2020 08:34">
<link url="http://xpto" document="y"/>
<link url="http://xpto" document="y"/>
<subjects number="2"><subject>Text explaining the previous link</subject><subject>Another text explaining the previous link</subject></subjects>
<link url="http://xpto" document="z"/>
<subjects number="1"><subject>Text explaining the previous link</subject></subjects>
<link url="http://xpto" document="y"/>
<link url="http://xpto" document="z"/>
</download>
目前,我可以使用此功能获取所有链接(这很容易实现):
import requests
from lxml import html
response = html.fromstring(requests.post(url_post, data=data).content)
links = response.xpath('//link')
正如我在 lxml 中指出的那样,如果存在主题,则旨在解释上一个链接。有时,它可以有多个主题(如上面的示例,其中一个主题有数字 2,这意味着它里面有两个“主题”项目,但其他“主题”只有一个主题)。它是一个很大的 lxml 文件,所以这种差异(很多链接,直到它有一个链接,后面有一个解释)经常发生。
我如何构建一个查询来获取所有这些链接,并且当它旁边的主题存在时(更准确地说,在链接之后),将它们放在一起或将其插入链接中?
我的梦想是这样的:
<link url="http://xpto" document="y" subjects="Text explaining the previous link| Another text explaining the thing"/>
同时包含链接和主题的列表也会有很大帮助。
[
[<link url="http://xpto" document="y"/>],
[<link url="http://xpto" document="y"/>, <subjects number="2"><subject>Text explaining the previous link</subject><subject>Another text explaining the previous link</subject></subjects>],
[<link url="http://xpto" document="y"/>],
]
当然,请随意提出不同的建议。
谢谢各位!
【问题讨论】:
-
“有时,它可以有多个主题。”是什么意思?您可以编辑问题并添加这样的案例示例吗?
-
嘿,@JackFleeting,我刚刚添加了更多解释。这是一个包含很多“链接”类别的列表,但链接后显示的“主题”部分实际上为我们提供了有关链接本身的解释。真是奇怪……因为是和链接有关的东西,要是进去就容易了。但这不是服务器响应的方式......太糟糕了。感谢您的关注!
-
@JackFleeting 我想我必须做一个'for循环'。也许有一个更好的方法可以用纯 lxml 做到这一点 - 顺便说一句,我不是很好......
-
我理解正确吗:你想要所有的
<link>元素,但是当后面跟着<subjects>元素时,你也需要这些吗? -
没错,@Grismar