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

Python3学习笔记8

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

以下是一个示例代码:

```python
from bs4 import BeautifulSoup

# 读取HTML文件
with open('example.html') as f:
    html = f.read()

# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')

# 获取所有的<img>标签
img_tags = soup.find_all('img')

# 为每个<img>标签添加width属性
for img in img_tags:
    img['width'] = 500

# 将修改后的HTML保存到新文件
with open('example_with_width.html', 'w') as f:
    f.write(str(soup))
```

在上面的示例代码中,我们首先使用Python内置的open函数读取了HTML文件,并使用BeautifulSoup解析HTML。然后,我们使用find_all方法查找所有的<img>标签,并使用Python的for循环为每个<img>标签添加了width属性。最后,我们将修改后的HTML保存到了一个新的文件中。

你需要将`example.html` 替换成你自己的HTML文件名,以及修改width属性的值。
发表评论 / Comment

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