2

嗨,有什么方法可以使用 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]

4

2 回答 2

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]
于 2019-03-12T15:26:02.063 回答
0

您可以通过 Element具有elementiterancestors()

您可以这样做:

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()]
于 2019-11-17T22:00:01.723 回答