【问题标题】:Python BS4 remove all div ID's Classes, Styles etcPython BS4 删除所有 div ID 的类、样式等
【发布时间】:2016-08-30 09:01:41
【问题描述】:

我正在尝试使用 BS4 解析站点中的 html 内容。我得到了我的 html 片段,但我需要删除所有标签类、ID、样式等。

例如:

<div class="applinks">
<div class="appbuttons">
<a href="https://geo.itunes.apple.com/ru/app/cloud-hub-file-manager-document/id972238010?mt=8&amp;at=11l3Ss" rel="nofollow" target="_blank" title="Cloud Hub - File Manager, Document Reader, Clouds Browser and Download Manager">Загрузить</a>
<span onmouseout="jQuery('.wpappbox-8429dd98d1602dec9a9fc989204dbf7c .qrcode').hide();" onmouseover="jQuery('.wpappbox-8429dd98d1602dec9a9fc989204dbf7c .qrcode').show();">QR-Code</span>
</div>
</div>

我需要得到:

<div>
<div>
<a href="https://geo.itunes.apple.com/ru/app/cloud-hub-file-manager-document/id972238010?mt=8&amp;at=11l3Ss" rel="nofollow" target="_blank" title="Cloud Hub - File Manager, Document Reader, Clouds Browser and Download Manager">Загрузить</a>
<span>QR-Code</span>
</div>
</div>

我的代码:

# coding: utf-8
import requests
from bs4 import BeautifulSoup


url = "https://lifehacker.ru/2016/08/29/app-store-29-august-2016/"
r = requests.get(url)
soup = BeautifulSoup(r.content)
post_content = soup.find("div", {"class","post-content"})
print post_content

我怎样才能删除所有标签属性?

【问题讨论】:

    标签: python html web-scraping tags beautifulsoup


    【解决方案1】:
    import requests
    from bs4 import BeautifulSoup
    
    
    url = "https://lifehacker.ru/2016/08/29/app-store-29-august-2016/"
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    for tag in soup():
        for attribute in ["class"]: # You can also add id,style,etc in the list
            del tag[attribute]
    

    【讨论】:

    • TypeError: 'Doctype' 对象不支持删除项目
    • 我已经在我的系统中使用您的网址进行了测试..它的工作原理..我不知道您为什么会收到此错误..您还可以查看 beautifulsoup 文档..以相同的方式。 .@KonstantinRusanov
    • 已修复。感谢您的帮助
    【解决方案2】:

    要从报废数据中的标签中删除所有属性:

    import requests
    from bs4 import BeautifulSoup
    
    def CleanSoup(content):
        for tags in content.findAll(True): 
            tags.attrs = {}
        return content
    
    
    url = "https://lifehacker.ru/2016/08/29/app-store-29-august-2016/"
    r = requests.get(url)
    soup = BeautifulSoup(r.content,"html.parser")
    post_content = soup.find("div", {"class","post-content"})
    post_content = CleanSoup(post_content)
    

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 2010-12-28
      • 2013-04-26
      • 2012-12-31
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多