用Python的BeautifulSoup库来修改html的属性值

Python3学习笔记8



用Python的BeautifulSoup库来修改html的属性值



以下是一个示例代码:



from bs4 import BeautifulSoup<br />
<br />
# 读取HTML文件<br />
with open('example.html') as f:<br />
&nbsp; &nbsp; html = f.read()<br />
<br />
# 使用BeautifulSoup解析HTML<br />
soup = BeautifulSoup(html, 'html.parser')<br />
<br />
# 获取所有的&lt;img&gt;标签<br />
img_tags = soup.find_all('img')<br />
<br />
# 为每个&lt;img&gt;标签添加width属性<br />
for img in img_tags:<br />
&nbsp; &nbsp; img['width'] = 500<br />
<br />
# 将修改后的HTML保存到新文件<br />
with open('example_with_width.html', 'w') as f:<br />
&nbsp; &nbsp; f.write(str(soup))<br />
```<br />
<br />
在上面的示例代码中,我们首先使用Python内置的open函数读取了HTML文件,并使用BeautifulSoup解析HTML。然后,我们使用find_all方法查找所有的&lt;img&gt;标签,并使用Python的for循环为每个&lt;img&gt;标签添加了width属性。最后,我们将修改后的HTML保存到了一个新的文件中。<br />
<br />
你需要将`example.html` 替换成你自己的HTML文件名,以及修改width属性的值。<br />
发表评论 / Comment

提示:本文章评论功能已关闭