Python 使用BeautifulSoup更新HTML文件

Python 使用BeautifulSoup更新HTML文件,python,html,beautifulsoup,Python,Html,Beautifulsoup,我希望能够使用BeautifulSoup保存对HTML文件所做的更改。我的脚本目前能够找到HTML文件中包含单词“data”的所有href,然后能够利用Google的url结果构建一个新的href。标记值打印正确,但问题是我无法看到输出文件中反映的更改,因为似乎没有更新Soup 更新以反映工作解决方案- # making the soup htmlDoc = open('test.html', "r+") soup = BeautifulSoup(htmlDoc) i = 0 #initial

我希望能够使用BeautifulSoup保存对HTML文件所做的更改。我的脚本目前能够找到HTML文件中包含单词“data”的所有href,然后能够利用Google的url结果构建一个新的href。标记值打印正确,但问题是我无法看到输出文件中反映的更改,因为似乎没有更新Soup

更新以反映工作解决方案-

# making the soup
htmlDoc = open('test.html', "r+")
soup = BeautifulSoup(htmlDoc)

i = 0 #initialize counter

for tag in soup.findAll(href=re.compile("data")): #match for href's with keyword data
    i += 1
    print i
    print tag.get_text()    
    text = tag.get_text() + "applications"
    g = pygoogle(text)
    g.pages = 1
    # print '*Found %s results*'%(g.get_result_count())
    if "http" in g.get_first_url(): 
        print g.get_first_url()
        new_tag = soup.new_tag("a", href=g.get_first_url())
        new_tag.string = tag.get_text()
        print new_tag
        tag.replace_with(new_tag)


print "Remaining"
print i

htmlDoc.close()

html = soup.prettify(soup.original_encoding)
with open("test.html", "wb") as file:
    file.write(html)

您已经创建了一个新标记
new\u tag=soup.new\u tag(“a”,href=g.get\u first\u url())
,但是您没有将
new\u tag
实际插入
HTML
代码,您只将其分配给变量
new\u tag

您需要使用提供的
insert()
append()
方法,才能将标记实际放置在html中

或者,您可以使用以下命令重新分配链接的
'href'

htmlDoc = open('test.html', "r+")
soup = BeautifulSoup(htmlDoc)

i = 0 #initialize counter

for tag in soup.findAll(href=re.compile("data")): #match for href's with keyword data
    i += 1
    print i
    print tag.get_text()    
    text = tag.get_text() + "applications"
    g = pygoogle(text)
    g.pages = 1
    # print '*Found %s results*'%(g.get_result_count())
    if "http" in g.get_first_url(): 
        print g.get_first_url()
        new_tag['href'] = g.get_first_url()

感谢您的帮助,我意识到我应该使用replace_with(),并且我也应该使用相同的输入文件进行输出。修改代码以显示我正在寻找的内容。