【问题标题】:Python strip document of image tags图像标签的 Python 条带文档
【发布时间】:2015-04-02 15:12:13
【问题描述】:

我想编写一个脚本,该脚本将在 Python 中从一个简单的 html 文件中删除所有图像,并将文件保存在适当的位置。

这是我的尝试:

from bs4 import BeautifulSoup, NavigableString

def strip_tags(html, invalid_tags):
    soup = BeautifulSoup(html)

    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = ""

            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = strip_tags(unicode(c), invalid_tags)
                s += unicode(c)

            tag.replaceWith(s)

    return soup

data ="C:\\Users\\ADMIN\\Documents\\webpage 1.htm"
with open(data) as orig_f:
        html = BeautifulSoup(orig_f.read())
        invalid_tags = ['img']
        print orig_f
        print strip_tags(orig_f, invalid_tags)

我正在努力解决两件事,首先代码运行时没有错误,但最后一行 print 什么也不打印,而前一行打印内存地址。我已经尝试搜索我的问题/阅读文档以了解我在这里做错了什么,但我很挣扎。

如何使此代码从我的 HTML 文件中删除所有图像标签,将其保存在适当位置的最佳做法是什么?

【问题讨论】:

    标签: python input beautifulsoup output edit


    【解决方案1】:

    “orig_f”是一个文件对象。如果要打印内容,一种方法是执行 orig_f.read() 或循环 f 并打印每一行。我认为这就是 strip_tags 函数返回 None 的原因。我没有使用 BeautifulSoap,所以不能说它会返回什么。

    为了就地保存,我总是在临时位置复制文件,并在覆盖当前文件之前打开临时文件进行读取。这是因为文件可能太大而无法存储在内存中,我处理大型 ascii 文件,如果一次性加载所有内容可能会崩溃。

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 2014-08-30
      • 2023-02-21
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多