【问题标题】:BeautifulSoup remove p tags with a classBeautifulSoup 删除带有类的 p 标签
【发布时间】:2021-09-08 12:43:10
【问题描述】:

我正在尝试 scrape 有一本小说,HTML 有几个 p 标签,其类类似于嵌入文本(在浏览器中不可见,但显示在 scraped 文本)并且我正在尝试删除它,类名称各不相同,所以我想删除具有类的 p 标签。 每一页的类名都会改变(它是一组随机字母) 这是 HTML 的一部分

<p>However, those musings dissipated as soon as he exited the school entrance.</p>
<p class="antvol">Visit lightnovelworld[.]com for a better experience</p>
<p>‘What’s going on. What’s going on!’</p>

预期结果:

    <p>However, those musings dissipated as soon as he exited the school entrance.</p>
    <p>‘What’s going on. What’s going on!’</p>
任何帮助将不胜感激,谢谢

【问题讨论】:

  • soup.find_all('p',class_=True) 成功了!

标签: python-3.x web-scraping beautifulsoup


【解决方案1】:

您可以使用.decompose() 方法删除标签。

由于您要删除的 &lt;p&gt; 标记有一个类 - antvol,因此首先选择该 &lt;p&gt; 标记并使用 .decompose() 将其删除。

这是如何完成的。

from bs4 import BeautifulSoup

s = '''<p>However, those musings dissipated as soon as he exited the school entrance.</p>
<p class="antvol">Visit lightnovelworld[.]com for a better experience</p>
<p>‘What’s going on. What’s going on!’</p>'''

soup = BeautifulSoup(s, 'lxml')
p = soup.find('p', class_='antvol')
p.decompose()

print(soup.prettify())
<html>
 <body>
  <p>
   However, those musings dissipated as soon as he exited the school entrance.
  </p>
  <p>
   ‘What’s going on. What’s going on!’
  </p>
 </body>
</html>

【讨论】:

猜你喜欢
  • 2020-10-27
  • 2014-10-02
  • 1970-01-01
  • 2020-02-26
  • 2020-10-24
  • 1970-01-01
  • 2013-04-12
  • 2013-10-19
  • 1970-01-01
相关资源
最近更新 更多