使用 python requests-HTML 获取标签的父元素

get parents element of a tag using python requests-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> 

我想获取 b 标签的所有父级:[html, body, p]

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

同优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]

您可以访问下层 lxml Element via the element attribute which has an iterancestors()

以下是您的操作方法:

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()]