gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:16:55 25 4
gpt4 key购买 nike

我收到了使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com