在html Python中重新应用img值

在html Python中重新应用img值,python,python-2.7,beautifulsoup,Python,Python 2.7,Beautifulsoup,我正在尝试将本地存储的html文件index.html中的“src”替换为“exampletext”字符串,代码如下: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(index.html) for img in soup.findAll('img'): img['src'] = 'exampletext ' 简单html代码: <html> <body> <a href="htt

我正在尝试将本地存储的html文件index.html中的“src”替换为“exampletext”字符串,代码如下:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(index.html)
for img in soup.findAll('img'):
    img['src'] = 'exampletext '
简单html代码:

<html>

<body>
<a href="http://simple_site"/>
<img src="http://www.samplesite.com/img1">

<a href="http://simple_site"/>
<img src="http://www.samplesite.com/picture2">

<a href="http://simple_site"/>
<img src="http://www.samplesite.com/gallery3">

</body>

</html>


但是这个代码不起作用,有人能帮忙吗?更改后如何保存对html文件的更改?

您的更新内容可以使用
打印(soup.prettify(“utf-8”)

因此,如果需要将其放回index.html文件中,只需将其写入其中:

updated_html = soup.prettify("utf-8")
with open('index.html', 'wb') as file:
    file.write(updated_html)

你可以使用正则表达式

import re  

repl = 'source'
html = re.sub('<img\s+src\s*=', '<' + repl + ' src=', s, flags=re.I)
重新导入
repl='source'

html=re.sub('您能提供一个html文件的最小示例吗?什么是“不工作”的意思?您打算在哪里“保存更改”?好的,我加上简单的code@kowal666,我仍然不清楚您打算将更改保存在何处。返回到同一个HTML文件,还是新文件?该文件是否可以在本地访问,或者您是否通过HTTP之类的方式检索它?您的代码会找到相关的标记并替换所需的标记。如果您
print(img)
after
img['src']
您将看到新内容。当然,此新内容不包含在您的ìndex.html`文件中。是否要将此新版本保存在那里?我将此代码与您的建议一起使用,但文件中没有任何更改。它适用于我,使用您提供的html(所有“img”标记替换为“source”)。你试过打印它吗?无论如何,我更新了一点代码,以防'img'是大写的OK,非常感谢,否则如何更改代码以仅替换src=“”中的值?你是指链接?尝试
'src=“(.*)”