4

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

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

我尝试了 BeatifulSoup。得到 AttributeError: 'NoneType' object has no attribute '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 标签

4

2 回答 2

4

解析器失败是因为您没有传递文件的内容,而是传递了路径字符串。因此,您正在搜索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
于 2013-11-05T12:49:42.103 回答
0

尝试使用append标签<a>insert_after在之后添加它<h1>

from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[1], 'r'))
h1 = soup.find('h1')
div = soup.new_tag('div')
a = soup.new_tag('a')
div.append(a)
h1.insert_after(div)
于 2013-11-05T12:49:13.783 回答