无法使用 lxml 将 html 个元素连接到某个标记

Can't get html elements connected to a certain tag using lxml

我创建了一个 xpath 表达式来从一些 html 元素中获取 a 标记。问题是我无法在控制台中打印它。

我希望得到的是使用 lxml 库连接到标签 a 的相关 html 元素。

这是我的尝试:

from lxml.html import fromstring

htmlcontent = """
<div class="post-taglist">
    <div class="grid">
        <a href="/questions/tagged/python"></a> 
    </div>
</div>
"""
root = fromstring(htmlcontent)
item = root.xpath("//*[@class='grid']/a")[0]
print(item)

我想要得到的输出:

<a href="/questions/tagged/python"></a>

我该怎么做?我用谷歌搜索了很多搜索词,但找不到这个问题的任何直接答案。

根据 docs 尝试以下操作:

from lxml.html import fromstring, tostring

htmlcontent = """
<div class="post-taglist">
    <div class="grid">
        <a href="/questions/tagged/python"></a> 
    </div>
</div>
"""

root = fromstring(htmlcontent)
item = root.xpath("//*[@class='grid']/a")[0]

print(tostring(item).strip())

这导致:

<a href="/questions/tagged/python"></a>