完成作业5 爬取图片
This commit is contained in:
27
test(3).py
Normal file
27
test(3).py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
|
||||||
|
import requests
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
|
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(1, 6):
|
||||||
|
# 使用不同的图片ID来获取不同的图片
|
||||||
|
# 方式1:使用随机图片(推荐)
|
||||||
|
url = f'https://picsum.photos/800/600?random={i}'
|
||||||
|
|
||||||
|
# 方式2:使用固定尺寸的特定ID图片(备选)
|
||||||
|
# url = f'https://picsum.photos/id/{i + 10}/800/600'
|
||||||
|
|
||||||
|
print(f"正在下载第 {i} 张图片...")
|
||||||
|
|
||||||
|
response = requests.get(url, headers=headers, timeout=10)
|
||||||
|
response.encoding = 'utf-8'
|
||||||
|
|
||||||
|
with open(f'image_{i}.jpg', 'wb') as f:
|
||||||
|
f.write(response.content)
|
||||||
|
|
||||||
|
print(f"第 {i} 张图片下载完成,保存为 image_{i}.jpg")
|
||||||
|
|
||||||
|
print("所有图片下载完成!")
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user