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

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

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

最佳答案

凭借出色的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]

关于python - 使用 python requests-HTML 获取标签的父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124725/

相关文章:

javascript - 如何使动态表格堆叠在彼此之下?而不仅仅是创建更多的数据单元

python - 如何在 Hangman 游戏中通过一次猜测激活多个字母?

Django rest 序列化具有不同读写数据类型的字段

python - Django 1.9 检查电子邮件是否已经存在

python - 如何为不同操作系统/Python 版本编译 Python C/C++ 扩展?

python - Pyautogui 键盘命令不适用于菜单栏分配

html - 禁止 Google 使用 robots.txt 将包含 "%2C"(逗号)的链接编入索引

python - 在 macOS 上更新 Homebrew python3 的 tcl/tk 版本

html - SVG 过滤器仅在添加到样式属性时才起作用 (Firefox)

python - 在python中提取不匹配的字符串