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)
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)))
获取所有
p
标记而不包含子标记的解决方案。你知道吗输出
这将获取
<p>
元素中的所有文本,但不会从<p>
中的任何子元素获取。Recursive必须等于false,否则它将查找子元素。我在另一个测试用例中添加了如下内容:<p><h4>Heading</h4></p>
假设BeautifulSoup 4.7+,您应该能够做到:
相关问题 更多 >
编程相关推荐