代码之家  ›  专栏  ›  技术社区  ›  SIM

无法使用lxml将html元素连接到特定标记

  •  2
  • SIM  · 技术社区  · 7 年前

    我创建了一个xpath表达式来达到 a 标记一些html元素。问题是我不能在控制台上打印它。

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

    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>
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gasanov    7 年前

    尝试以下内容,基于 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>