python - BeautifulSoup:删除小部件

标签 python web-scraping beautifulsoup

我有一个<twitterwidget>page上需要删除(不需要推文中的文本)。 我试过了

for script in soup(["script", "style"]):
        script.extract()  

但这并没有帮助,推文中的文本仍然存在。 我还尝试删除单独的 p与推文:

for s in soup('p'):
   try:
       if s["lang"]=="en":
         s.extract()
   except:
        pass

但这只是部分解决方案 - 来自 twitterwidget 的一些垃圾还留在那里.. 我怎样才能一劳永逸地摆脱那个小部件?

最佳答案

只需提取 twitterwidget 元素本身,它就会完全删除它,包括它的所有后代:

from bs4 import BeautifulSoup

html = """<div>foobar</div> <twitterwidget class="twitter-tweet twitter-tweet-rendered" id="twitter-widget-0" data-tweet-id="763961058490933248" style="position: static; visibility: visible; display: block; transform: rotate(0deg); max-width: 100%; width: 500px; min-width: 220px; margin-top: 10px; margin-bottom: 10px;"></twitterwidget>"""
soup  = BeautifulSoup(html)

soup.find("twitterwidget").extract()
print(soup)

输出:

<html><body><div>foobar</div> </body></html>

关于python - BeautifulSoup:删除小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39021114/

相关文章:

python - 无法使用pycharm调试 flask 应用程序

python - 当我不使用 BeautifulSoup 时如何摆脱 BeautifulSoup html 解析器错误

python - 使用Python抓取谷歌搜索结果标题和网址

python - 在 Python 3 (urllib) 中打印 http 状态代码

python - Django + celery - 为什么我的周期性任务没有运行?

Python Timedelta64 将天数转换为月数

css - 使用 rvest 从 CSS 中抓取标题属性

javascript - 通过 Selenium 抓取动态内容?

python scrapy从网站中提取数据

Python3 Beautiful Soup 获取HTML标签 anchor