<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/