python 用beautifulsoup库解析网页并插入标签

好的,以下是使用BeautifulSoup库解析网页并插入标签的Python代码:

```python
from bs4 import BeautifulSoup

# 读取HTML文件
with open('index.html', 'r') as file:
    html = file.read()

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

# 查找需要插入标签的元素
target = soup.find('p', {'id': 'content'})

# 创建新的标签
new_tag = soup.new_tag('span')
new_tag.string = 'New Content'

# 将新标签插入到目标元素后面
target.insert_after(new_tag)

# 打印修改后的HTML代码
print(soup.prettify())
```

以上代码假设需要修改一个id为"content"的p标签,在其中插入一个新的span标签,并在其中添加文本"New Content"。修改后的HTML代码将通过`soup.prettify()`方法输出。

相关代码参考