gpt4 book ai didi

python - 如何使用python在h1标签之后在现有html文件中添加新的div标签

转载 作者:太空狗 更新时间:2023-10-30 03:03:14 24 4
gpt4 key购买 nike

我有一个 html 文件,我想在 h1 标签后添加一个 div 标签。 div 标签将有一个 anchor 标签。我如何使用 python 编辑现有的 html 文件并添加带有链接的 div 这就是我想做的

<h1>
</h1>
<div> <a></a>
</div>

我尝试使用 BeatifulSoup。得到 AttributeError: 'NoneType' 对象没有属性 'insert_after' 这个错误:

htmlFile ='path to html file' 
soup = Soup(htmlFile)
headTag = soup.find('h1')
divTag = soup.new_tag('div')
divTag['class'] = "link"
headTag.insert_after(divTag)

建议修改这段代码,在当前html文件中加入div标签

最佳答案

解析器失败是因为您没有传递文件内容,而是传递了路径字符串。因此,您正在路径中搜索 h1 标记,但解析器找不到它。

htmlFile = open('path to html file').read()

完整代码:

with open("path to html file") as file:
htmlFile = file.read()
soup = Soup(htmlFile)
headTag = soup.find('h1')
divTag = soup.new_tag('div')
divTag['class'] = "link"
headTag.insert_after(divTag)
print(soup) #This should print the new, modified html

关于python - 如何使用python在h1标签之后在现有html文件中添加新的div标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789279/

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