You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Python和Beautiful Soup下载DCInside帖子图片失败问题

解决DCInside帖子图片无法下载的问题

我帮你排查了代码里的几个关键问题,调整后应该能顺利下载目标帖子里的图片了:

代码里的问题点

  • 导入与调用不匹配:你用from requests import get导入了requests的get方法,但后续代码里却用requests.get()调用,这会触发NameError。
  • 变量名拼写错误:定义了img_url但后续写成了image_url,同样会导致变量未定义的错误。
  • 没必要用PIL中转:直接通过requests获取图片二进制内容保存更高效,还能避免PIL处理时可能出现的格式或权限问题。
  • 图片请求缺少headers:DCInside的图片资源会校验请求头,直接请求图片URL很容易被拦截返回403。

修正后的代码

import requests
from bs4 import BeautifulSoup

headers = {
    "Connection": "keep-alive",
    "Cache-Control": "max-age=0",
    "sec-ch-ua-mobile": "?0",
    "DNT": "1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Sec-Fetch-Site": "none",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-User": "?1",
    "Sec-Fetch-Dest": "document",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "ko-KR,ko;q=0.9"
}

test_url = 'https://gall.dcinside.com/mgallery/board/view/?id=irudagall&no=18887&page=2027'
test_res = requests.get(test_url, headers=headers)
test_soup = BeautifulSoup(test_res.text, "lxml")

# 获取图片链接
img_url = test_soup.find("ul", {"class": "appending_file"}).find("a")['href']
# 确保图片链接是完整的HTTPS链接(如果返回的是相对路径的话)
if not img_url.startswith('http'):
    img_url = f'https:{img_url}'

# 请求图片并保存
img_res = requests.get(img_url, headers=headers)
with open('image.jpg', 'wb') as f:
    f.write(img_res.content)

print("图片下载完成!")

关键修正说明

  1. 统一使用import requests,避免导入方式混淆导致的错误。
  2. 修正变量名img_url的拼写,确保前后一致。
  3. 给图片请求也带上相同的headers,模拟浏览器请求绕过反爬拦截。
  4. 增加了相对路径判断,防止图片链接是相对路径导致请求失败。
  5. 直接将图片二进制内容写入文件,省去PIL中转步骤,更稳定高效。

内容的提问来源于stack exchange,提问作者ejcho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:37:29