gpt4 book ai didi

python - BeautifulSoup 标签删除意外结果

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

所以我写了一些代码来只提取 <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

关于python - BeautifulSoup 标签删除意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18857504/

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