如何找到P标签,其中没有兄弟姐妹在它使用美丽的汤

2024-04-25 16:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

一些<p></p>标记有<img>标记和<h4>标记,但我只想要那些<p>标记,其中没有同级标记,只有内容。你知道吗

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

我想要<p>标签,没有<img>标签,使用漂亮的汤


Tags: 标记srcurl内容helloimgworldany
3条回答

获取所有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>]

这将获取<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)))

假设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)

相关问题 更多 >