【问题标题】:get parents element of a tag using python requests-HTML使用 python requests-HTML 获取标签的父元素
【发布时间】:2023-03-07 16:22:01
【问题描述】:

你好,有什么方法可以使用 requests-HTML 获取标签的所有父元素?

例如:

<!DOCTYPE html>
<html lang="en">
<body id="two">
    <h1 class="text-primary">hello there</h1>
    <p>one two tree<b>four</b>five</p>
</body>
</html> 

我想得到b标签的所有父母:[html, body, p]

或者对于h1标签得到这个结果:[html, body]

【问题讨论】:

    标签: python html python-3.x web-crawler python-requests-html


    【解决方案1】:

    与优秀的lxml

    from lxml import etree
    html = """<!DOCTYPE html>
    <html lang="en">
    <body id="two">
        <h1 class="text-primary">hello there</h1>
        <p>one two tree<b>four</b>five</p>
    </body>
    </html> """
    tree = etree.HTML(html)
    # We search the first <b> element
    b_elt = tree.xpath('//b')[0]
    print(b_elt.text)
    # -> "four"
    # Walking around ancestors of this <b> element
    ancestors_tags = [elt.tag for elt in b_elt.iterancestors()]
    print(ancestors_tags)
    # -> [p, body, html]
    

    【讨论】:

      【解决方案2】:

      您可以通过具有iterancestors()element 属性访问较低级别的lxml Element

      你可以这样做:

      from requests_html import HTML
      
      html = """<!DOCTYPE html>
         <html lang="en">
         <body id="two">
             <h1 class="text-primary">hello there</h1>
             <p>one two tree<b>four</b>five</p>
          </body>
      </html>"""
      html = HTML(html=html)
      b = html.find('b', first=True)
      parents = [a for a in b.element.iterancestors()]
      

      【讨论】:

      • 什么是'a' in parents = [a for a in b.element.iterancestors()] ?
      • D.O.这是列表理解等价于 list = [] for a in b.element.iterancestors(): list.append(a)
      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 2020-02-01
      • 2013-05-13
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多