我一直在开发一个可以从各种URL下载图像并将其上传到AWS S3的Python脚本.我的脚本在多个域中运行良好,但在try 从特定URL(https://www.net-a-porter.com/variants/images/17266703523615883/in/w920_a3-4_q60.jpg)下载图像时遇到超时错误.

我试图通过增加超时和添加标头来排除故障,但问题仍然存在.

import requests
import tempfile
import os

def upload_image_to_s3_from_url(self, image_url, filename, download_timeout=120):
    """
    Downloads an image from the given URL to a temporary file and uploads it to AWS S3,
    then returns the S3 file URL.
    """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8'
        }
        response = requests.get(image_url, timeout=download_timeout, stream=True, headers=headers)
        response.raise_for_status()
        
        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
            for chunk in response.iter_content(chunk_size=8192):
                tmp_file.write(chunk)
            
            file_url = self.upload_image_to_s3(tmp_file.name, filename)
        
        os.unlink(tmp_file.name)
        return file_url
    except requests.RequestException as e:
        raise Exception(f"Failed to download or upload image. Error: {e}")

遇到错误: Exception: Failed to download or upload image. Error: HTTPSConnectionPool(host='www.net-a-porter.com', port=443): Read timed out. (read timeout=60)

我试过了:

  1. 将DOWNLOAD_TIMEOUT增加到更高的值
  2. 修改请求头以模拟真实的浏览器会话

这种方法适用于来自其他域的图像,但不适用于上面提到的URL.

如有任何见解或建议,我们将不胜感激.提前感谢您的帮助!

推荐答案

我怀疑,主机已经准备好了某种刮板检测,并通过比较User Agent来阻止请求.

我可以通过将其更改为:

"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36",

Python-3.x相关问答推荐

Python gpsd客户端

在Python中从列创建新行

数据类对象列表的字典获取方法-在数据类列表中查找具有特定变量值的数据类

如何将项目添加到Python中具有固定大小的列表列表中

Python中提取每个组/ID所属特定列中的自然数

Pandas教程:如何更新行内数值的位置

通过 Pandas 通过用户定义函数重命名数据框列

以不规则频率识别数据框日期时间列上缺失的日期,并用关联值填充它们

Python ** 用于负数

如何在数据['column']中的'string'等条件下应用pandas

协议不支持地址系列在将 Scapy L3socket 与 WSL 一起使用时

Pytorch:图像标签

保存 StandardScaler() 模型以用于新数据集

如何在 Python 3 中通过 IP 获取 WhoIs 信息?

在数据类中创建类变量的正确方法

ImportError:无法导入名称cross_validate

如何找出从哪个模块导入名称?

try 在 Mac OS 中运行此命令pipenv install requests时出错

如何对字典的函数输出列表进行单元测试?

如何使用 Celery 和 Django 将任务路由到不同的队列