Skip to main content
 首页 » 编程设计

python之Scrapy下载文件报错302

2025年05月04日12lovecherry

为什么我会收到此错误消息?

[scrapy] WARNING: File (code: 302): Error downloading file from <GET <url> referred in <None> 

该 URL 在我的浏览器中似乎可以毫无问题地下载,302 只是一个重定向。为什么 scrapy 不直接按照重定向来下载文件?

process = CrawlerProcess({ 
    'FILES_STORE': 'C:\\Users\\User\\Downloads\\Scrapy', 
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 
    'ITEM_PIPELINES': {'scrapy.pipelines.files.FilesPipeline': 1}, 
}) 
 
process.crawl(MySpider) 
process.start()  # the script will block here until the crawling is finished 

请您参考如下方法:

我的解决方案是先使用 requests 发送 http 请求,根据 status_code 选择要下载的 url,现在您可以将 url 放在 file_urls 或您的自定义名称中。

import requests 
 
def check_redirect(url): 
    response = requests.head(url) 
    if response.status_code == 302: 
        url = response.headers["Location"] 
    return url 

或者您可以使用自定义文件管道

class MyFilesPipeline(FilesPipeline): 
 
def handle_redirect(self, file_url): 
    response = requests.head(file_url) 
    if response.status_code == 302: 
        file_url = response.headers["Location"] 
    return file_url 
 
def get_media_requests(self, item, info): 
    redirect_url = self.handle_redirect(item["file_urls"][0]) 
    yield scrapy.Request(redirect_url) 
 
def item_completed(self, results, item, info): 
    file_paths = [x['path'] for ok, x in results if ok] 
    if not file_paths: 
        raise DropItem("Item contains no images") 
    item['file_urls'] = file_paths 
    return item 

我在这里使用了其他解决方案 Scrapy i/o block when downloading files