python - 我需要选择一个具有 beautifulsoup 特定子标签的 div 标签

标签 python python-3.x beautifulsoup

<div class = "some class">
    <h4>X1</h4>
    <a href="www.someurl.com">Value of X1</a>
</div>

我需要选择具有特定 h4 匹配文本 X1 的 div。通过使用具有特定属性的 find_all() ,然后再次使用 find_all 转到 h4 选择 h4 而不是 div 本身。我需要选择 div。

如果上述可行,有什么方法可以直接访问“a”标签?

最佳答案

看起来您需要 findNext 方法。

例如:

from bs4 import BeautifulSoup


html = """<div class = "some class">
    <h4>X1</h4>
    <a href="www.someurl.com">Value of X1</a>
</div>"""

soup = BeautifulSoup(html, "html.parser")
for tag in soup.find_all("h4", text="X1"):     #Find all h4 with required text. 
    print(tag.findNext("a").text)

输出:

Value of X1

关于python - 我需要选择一个具有 beautifulsoup 特定子标签的 div 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52659782/

相关文章:

python - 如何在本地使用 sageMath 安装 Theano 库?

python - 使用另一个 python 文件中的变量

python-3.x - 在使用 COPY 将大表读入 pandas 数据帧时使用参数化 SQL 查询

javascript - 单击 Javascript 链接以在 Python 中发出发布请求

python - 十六进制字符串到python中的字符

python - 遍历 Django 模板中的多个列表

python - 更改 cx_Freeze 脚本的图标

python - 如何使用 Beautiful Soup 收集元素?

python - 在网站上使用 python Beautiful Soup 时,不断收到此错误 : urllib. error.HTTPError: HTTP Error 403: Forbidden

python - 阻止 python 生成 pyc 文件