用python写一个爬取页面所有1080P图片的代码
入门文章 2
写清楚每行代码的注释
-
“`Python
# 导入需要的模块
import re
import requests
from bs4 import BeautifulSoup# 定义要爬取的图片尾缀名
image_type = [“jpg”, “png”, “jpeg”]# 请求页面
url = “http://www.example.com”
response = requests.get(url)# 构建BeautifulSoup对象
soup = BeautifulSoup(response.content, “html.parser”)# 查找所有图片链接
img_links = soup.find_all(“img”, src=re.compile(“.*?.jpg”))# 下载高清1080P的图片
for link in img_links:
if link[“src”].split(“.”)[-1] in image_type:
print(“正在处理:”, link[“src”])
response = requests.get(link[“src”])
with open(“F:/python/img/%s.jpg” % link[“src”].split(“/”)[-1], “wb”) as f:
f.write(response.content)print(“图片处理完毕!”)
“`2023年3月15日 下午10:24