diff --git a/260326-2509165039.py b/260326-2509165039.py new file mode 100644 index 0000000..b9d5cba --- /dev/null +++ b/260326-2509165039.py @@ -0,0 +1,37 @@ +import requests +from bs4 import BeautifulSoup +import time + +count=5 +url = f'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'} +print(f"开始爬取{count}张图片...") + +for i in range(1,count+1): + try: + 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}]正在下载:{img_src}") + + img_response = requests.get(img_src, timeout=10) + + filename = f'image_{i}.jpg' + + with open(filename, 'wb') as f: + f.write(img_response.content) + print(f" -> 成功保存为{filename}") + else: + print(f"[{i}]未找到图片标签") + + time.sleep(1) + + except Exception as e: + print(f"[{i}]发生错误:{e}") + +print("全部下载完成!") \ No newline at end of file