完成作业五—爬图片

This commit is contained in:
2509165046
2026-03-26 19:38:52 +08:00
parent ea6772a146
commit bc272de404

26
爬图片.py Normal file
View File

@@ -0,0 +1,26 @@
import requests
from bs4 import BeautifulSoup
import time
url = 'https://picsum.photos/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
}
for i in range(5):
print(f'正在爬取第 {i+1} 张图片...')
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
img_tag = soup.select_one('img.resize')
if img_tag:
img_src = img_tag.get('src')
print(f'{i+1} 张图片URL{img_src}')
img_response = requests.get(img_src, timeout=10)
with open(f'image_{i+1}.jpg', 'wb') as f:
f.write(img_response.content)
print(f'{i+1} 张图片下载完成!\n')
time.sleep(1)
else:
print(f'{i+1} 张图片未找到,跳过\n')