Python爬虫求助:无法下载指定规则的网页图片(附问题代码)
问题分析与修复
先说说你代码里的几个关键问题:
- 导入了一堆没用的库(pyautogui、selenium这些),只会增加冗余
- 遍历soup的方式错了,直接遍历soup拿不到图片链接,得专门找
<img>标签 - 方法名写错了:
startswitch→startswith,endswitch→endswith - 保存文件名的逻辑完全混乱,没法生成合法的文件名
- 没检查目标文件夹是否存在,直接保存会报错
下面是修正后的代码,每一步都加了注释:
import requests from bs4 import BeautifulSoup import urllib.request import os # 目标网页URL url = "https://parkmu123.neocities.org/question" # 图片保存路径,注意替换成你自己的路径 img_dest = "c:/users/root/desktop/img/" # 先创建保存文件夹,不存在就新建 if not os.path.exists(img_dest): os.makedirs(img_dest) # 请求网页并解析 res = requests.get(url) res.encoding = res.apparent_encoding # 解决网页编码乱码问题 soup = BeautifulSoup(res.text, "html.parser") # 遍历页面所有img标签 for idx, img_tag in enumerate(soup.find_all('img')): img_src = img_tag.get('src') # 跳过空的图片链接 if not img_src: continue # 判断链接是否是目标域名下的jpg或gif格式 if img_src.startswith("parkmu123.neocities.org/") and (img_src.endswith(".jpg") or img_src.endswith(".gif")): # 补全相对路径为完整URL if not img_src.startswith("http"): img_src = f"https://{img_src}" # 提取图片原文件名 filename = os.path.basename(img_src) # 拼接完整保存路径 save_path = os.path.join(img_dest, filename) # 下载图片并捕获异常 try: urllib.request.urlretrieve(img_src, save_path) print(f"成功下载:{filename}") except Exception as e: print(f"下载失败 {img_src}:{str(e)}")
额外说明:
- 增加了编码处理,避免网页内容解析乱码
- 处理了相对路径的情况,自动补成全URL
- 加入异常捕获,遇到下载失败的情况不会直接崩溃
- 用
os.path.join处理路径,避免Windows系统的路径分隔符问题
内容的提问来源于stack exchange,提问作者임민서
相关产品推荐
相关产品推荐

