Skip to main content
 首页 » 编程设计

python之无法使用lxml获取连接到特定标签的html元素

2024年12月31日7thcjp

我创建了一个 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>