一些<p></p>标签有<img>标签和<h4>标签,但我只想要那些<p>标签,其中没有兄弟标签在它只是内容。
<p> <img src="any url"/> </p> <p> hello world </p>我想要没有使用漂亮汤的<img>标签的<p>标签
发布于 2019-01-28 16:48:20
这将获得<p>元素中的所有文本,但不会从<p>中的任何子元素中获得这些文本。Recursive需要等于false,否则它将查找子元素。我添加了另一个测试用例来展示这一点:<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)))发布于 2019-01-30 03:50:40
一种解决方案,可以获取所有没有子标签的p标签。
import bs4
html="""<p> <img src="any url"/> </p> <p> hello world </p>"""
soup=bs4.BeautifulSoup(html,"html.parser")
def has_no_tag_children(tag):
if type(tag) is bs4.element.Tag: #check if tag
if tag.name =='p': #check if it is p tag
if bs4.element.Tag not in [type(child) for child in tag.children]: # check if has any tag children
return True
return False
kids=soup.find_all(has_no_tag_children)
print(kids)输出
[<p> hello world </p>]发布于 2019-01-30 04:12:23
假设使用BeautifulSoup 4.7+,您应该能够这样做:
import bs4
html="""<p> <img src="any url"/> </p> <p> hello world </p>"""
soup=bs4.BeautifulSoup(html,"html.parser")
kids=soup.select("p:not(:has(*))")
print(kids)https://stackoverflow.com/questions/54397779
复制相似问题