如何在此html代码片段中获取a的href值?使用xpath/python选择特定节点的父节点
我需要得到它基于该类在我标记
<!--
<a href="https://link.com" target="_blank"><i class="foobar"></i> </a>
-->
我想这一点,但我没有得到任何结果
foo_links = tree.xpath('//a[i/@class="foobar"]')
如何在此html代码片段中获取a的href值?使用xpath/python选择特定节点的父节点
我需要得到它基于该类在我标记
<!--
<a href="https://link.com" target="_blank"><i class="foobar"></i> </a>
-->
我想这一点,但我没有得到任何结果
foo_links = tree.xpath('//a[i/@class="foobar"]')
您的代码不会对我的工作 - 它返回一个列表的<a>
。如果你想的href
不是元素本身的列表,添加/@href
:
hrefs = tree.xpath('//a[i/@class="foobar"]/@href')
你也可以先找到<i>
S,然后用/parent::*
(或简称/..
)要回的<a>
秒。
hrefs = tree.xpath('//a/i[@class="foobar"]/../@href')
# ^ ^^
# | | obtain the 'href'
# | |
# | get the parent of the <i>
# |
# find all <i class="foobar"> contained in an <a>.
如果所有这些都不起作用,您可能需要验证文档的结构是否正确。
请注意,XPath不会在评论<!-- -->
内偷看。如果<a>
确实在注释<!-- -->
中,则需要首先手动提取文档。
hrefs = [href for comment in tree.xpath('//comment()')
# find all comments
for href in lxml.html.fromstring(comment.text)
# parse content of comment as a new HTML file
.xpath('//a[i/@class="foobar"]/@href')
# read those hrefs.
]
你应该注意到,目标元素是HTML
评论。你不能简单地得到<a>
从评论与XPath
像"//a"
像在这种情况下,它不是一个节点,但简单的字符串。
试试下面的代码:
import re
foo_links = tree.xpath('//comment()') # get list of all comments on page
for link in foo_links:
if '<i class="foobar">' in link.text:
href = re.search('\w+://\w+.\w+', link.text).group(0) # get href value from required comment
break
附:您可能需要使用更复杂的正则表达式来匹配链接URL
这似乎是最好的。评论/ <! - 正在捣乱。 我确实增加了一个额外的。\ w +来获取URL的其余部分。出于某种原因,我一次只能获得一条记录,而每次我运行它时都会得到一条不同的记录。可能有一些问题附加到我创建的列表中。谢谢 –
删除了'break',我得到了我之后的东西 –
只是好奇为什么不只是'/ a/@ href'? – SomeDude
@svasa OP说:“*我需要得到它的基础上,我在标记类*” – kennytm
好吧没有看到。得到它了。 – SomeDude