在html Python中实现img值

2024-05-08 02:57:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用html文件中的“exampletext”字符串替换“src”索引.html使用此代码存储在本地:

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文件?你知道吗


Tags: 文件代码srccomhttpimghtmlwww
2条回答

您的更新内容可以用print(soup.prettify("utf-8"))
打印 所以,如果你需要把它放到索引.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)

相关问题 更多 >