Skip to main content
 首页 » 编程设计

python之BeautifulSoup 标签删除意外结果

2025年05月04日11artech

所以我写了一些代码来只提取 <p> 中的内容一些 HTML 代码的标签。这是我的代码

soup = BeautifulSoup(my_string, 'html') 
no_tags=' '.join(el.string for el in soup.find_all('p', text=True)) 

对于它运行的大多数示例,它都按照我希望的方式工作,但我注意到在诸如

<p>hello, how are you <code>other code</code> my name is joe</p> 

它什么都不返回。我想这是因为 <p> 中还有其他标签标签。所以要明确一点,我希望它返回的是

hello, how are you my name is joe 

也就是说,我想要 <p> 中的所有内容标签,但只有第一层。我想忽略 <p> 中其他标签中包含的所有内容。标签。 有人可以帮我解决如何处理此类示例吗?

请您参考如下方法:

您好,我认为您可以使用它来提取 p 标签内的文本。

my_string = "<p>hello, how are you <code>other code</code> my name is joe</p>" 
soup = BeautifulSoup(my_string, 'html') 
 
soup.code.extract() 
text = soup.p.get_text() 
print text