python - 使用 python BeautifulSoup 从 HTML 中删除具有特定 id 内容的特定标签

标签 python html tags beautifulsoup

我收到了使用 BeautifulSoup 从 HTML 中删除具有特定 id 的标签的建议。例如删除 <div id=needDelete>...</div>以下是我的代码,但似乎无法正常工作:

import os, re
from bs4 import BeautifulSoup

cwd = os.getcwd()
print ('Now you are at this directory: \n' + cwd)

# find files that have an extension with HTML
Files = os.listdir(cwd)
print Files

def func(file):
    for file in os.listdir(cwd):
        if file.endswith('.html'):
            print ('HTML files are \n' + file)
            f = open(file, "r+")
            soup = BeautifulSoup(f, 'html.parser')
                matches  = str(soup.find_all("div", id="jp-post-flair"))
                #The soup.find_all part should be correct as I tested it to             
                #print the matches and the result matches the texts I want to delete.
                f.write(f.read().replace(matches,''))
                #maybe the above line isn't correct
            f.close()
func(file)

您能帮忙检查一下哪个部分的代码有错误吗?也许我应该如何处理它? 非常感谢!!

最佳答案

您可以使用.decompose() method删除元素/标签:

f = open(file, "r+")

soup = BeautifulSoup(f, 'html.parser')
elements = soup.find_all("div", id="jp-post-flair")
for element in elements:
  element.decompose()

f.write(str(soup))

还值得一提的是,您可能只使用 .find() 方法,因为 id 属性在文档中应该是唯一的(这意味着可能会有大多数情况下仅是一个元素):

f = open(file, "r+")

soup = BeautifulSoup(html_doc, 'html.parser')
element = soup.find("div", id="jp-post-flair")
if element:
  element.decompose()

f.write(str(soup))
<小时/>

作为替代方案,基于以下评论:

  • 如果你只想解析和修改文档的一部分,BeautifulSoup有一个SoupStrainer class这允许您有选择地解析文档的某些部分。

  • 您提到 HTML 文件中的缩进和格式正在更改。您可以查看相关的 output formatting section 而不是直接将 soup 对象直接转换为字符串。在文档中。

    根据所需的输出,以下是一些可能的选项:

    • soup.prettify(formatter="minimal")
    • soup.prettify(formatter="html")
    • soup.prettify(formatter=None)

关于python - 使用 python BeautifulSoup 从 HTML 中删除具有特定 id 内容的特定标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396627/

相关文章:

python - 如何上传图片并在 Google Cloud Bucket 中公开

jquery - 正确切换类

javascript - 容器内的行在顶部被遮挡

html - CSS图片div的定位

c# - 在 Visual Studio XML 文档中同时使用 <value> 和 <summary> 标签的目的

css - 如何左对齐来 self 的 Magento 商店页脚处的 cms block 的 IMG 元素

python - 测试 children 标签是否存在于 beautifulsoup 中

python - PysimpleGui - 国际象棋示例中关于 size=(1, 1) 和图像着色的混淆

python - 如何在 Python 2.7 中访问 ODB 文件

python - 有没有办法在 environment.yml 中具有特定于平台的依赖项?