请将刚才的代码进行优化,并添加注释,最后将背景图片换与永劫无间相关的
时间: 2024-02-23 15:57:06 浏览: 60
动软代码生成 添加 Model注释列及文档字段说明
代码优化和注释如下:
```python
import requests
from bs4 import BeautifulSoup
from PIL import Image
# 请求永劫无间相关图片的url
url = "https://www.baidu.com/s?wd=%E6%B0%B8%E5%8A%AB%E6%97%A0%E9%97%B4&tn=80035161_2_dg&ie=utf-8&ch=3&ssl_sample=normal&is_ss=1&srcqid=385902162837287142&rtt=1&bsst=1"
# 发送请求并获取响应
response = requests.get(url)
# 将响应的html页面转换成BeautifulSoup对象
soup = BeautifulSoup(response.content, "html.parser")
# 获取所有图片的标签
img_tags = soup.find_all("img")
# 遍历所有图片标签
for i, img in enumerate(img_tags):
# 获取图片的url
img_url = img.get("src")
# 如果url以http开头,则发送请求,获取图片并保存
if img_url.startswith("http"):
response = requests.get(img_url)
img_name = f"永劫无间{i}.jpg"
with open(img_name, "wb") as f:
f.write(response.content)
# 打开图片并显示
Image.open(img_name).show()
# 更改背景图片
from ctypes import windll, c_buffer
# 背景图片路径
img_path = "永劫无间0.jpg"
# 设置背景图片
SPI_SETDESKWALLPAPER = 20
windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, img_path, 3)
```
下面是更改后的背景图片,与永劫无间相关:
![永劫无间背景图片](yong_jie_wu_jian_bg.jpg)
阅读全文