gpt4 book ai didi

python - 如何使用 Beautiful soup 查找其中没有 sibling 的 P 标签

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:28 25 4
gpt4 key购买 nike

一些 <p></p>标签有 <img>标记和 <h4>标签,但我只想要那些 <p>没有兄弟标签的标签只是内容。

 <p> <img src="any url"/> </p>     <p> hello world </p>

我要<p>没有 <img> 的标签标签使用 BeautifulSoup

最佳答案

这将获取 <p> 中的所有文本元素,但不会从 <p> 中的任何子元素中获取它.递归需要等于假,否则它将查看子元素。我添加了另一个测试用例供您展示:<p><h4>Heading</h4></p>

from bs4 import BeautifulSoup

html = "<p> <img src='any url'/> </p> <p><h4>Heading</h4></p> <p> hello world </p>"

soup = BeautifulSoup(html)

for element in soup.findAll('p'):
print("".join(element.findAll(text=True, recursive=False)))

关于python - 如何使用 Beautiful soup 查找其中没有 sibling 的 P 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54397779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com