【问题标题】:BeautifulSoup removing tagsBeautifulSoup 去除标签
【发布时间】:2014-02-09 03:01:15
【问题描述】:

我正在尝试从源中删除样式标签及其内容,但它不起作用,没有错误只是不会分解。这就是我所拥有的:

source = BeautifulSoup(open("page.html"))
getbody = source.find('body')
for child in getbody[0].children:
    try:
        if child.get('style') is not None and child.get('style') == "display:none":
            # it in here
            child.decompose()
    except:
        continue
print source
# display:hidden div's are still there.

【问题讨论】:

  • 您的语法无效;没有except 处理程序。如果您使用except: pass 删除 try/except 来查看您正在掩盖的任何错误。
  • getbody[0] 也会引发KeyError
  • 我不知道这段代码怎么不会抛出任何SyntaxError

标签: python beautifulsoup


【解决方案1】:

以下代码可以满足您的要求并且可以正常工作; 不要使用毯子,除了处理来掩盖错误:

source = BeautifulSoup(open("page.html"))
for hidden in source.body.find_all(style='display:none'):
    hidden.decompose()

或者更好的是,使用正则表达式将网络扩大一点:

import re

source = BeautifulSoup(open("page.html"))
for hidden in source.body.find_all(style=re.compile(r'display:\s*none')):
    hidden.decompose()

Tag.children 仅列出body 标记的直接 个子级,而不是所有嵌套的子级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2012-05-18
    • 2011-03-31
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    相关资源
    最近更新 更多