下面是使用Beautiful Soup库替换返回的图像源的一部分的代码示例:
from bs4 import BeautifulSoup
# 假设返回的HTML文档如下
html = '''
'''
# 创建Beautiful Soup对象并解析HTML文档
soup = BeautifulSoup(html, 'html.parser')
# 获取图像标签
img_tag = soup.find('img')
# 获取图像源URL
img_src = img_tag['src']
# 替换图像源的一部分
new_img_src = img_src.replace('example.com', 'newexample.com')
# 更新图像标签的src属性
img_tag['src'] = new_img_src
# 打印修改后的HTML文档
print(soup.prettify())
在上面的示例中,我们首先将HTML文档传递给Beautiful Soup库的BeautifulSoup
类来创建一个Beautiful Soup对象。然后,我们使用find
方法找到图像标签,并使用['src']
访问其src属性来获取图像源URL。接下来,我们使用replace
方法将图像源的一部分替换为新的URL。最后,我们更新图像标签的src属性,并使用prettify
方法打印修改后的HTML文档。