使用Python请求的不同响应

2024-04-25 01:15:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用requests从URL下载图像。使用浏览器或REST客户机,比如restlet chrome extension,我可以检索正常的内容、json和可以保存到磁盘的二进制图像。你知道吗

使用requests作为响应结果,我得到了几乎相同的响应头,只有Content-Length具有不同的值—15字节而不是35 KB—并且我找不到二进制图像。你知道吗

为了模拟浏览器发出的请求,我配置了相同的请求头,如下所示:

headers = {"Host": "cpom.prefeitura.sp.gov.br",
           "Pragma": "no-cache",
           "Cache-Control": "no-cache",
           "DNT": "1",
           "Accept": "*/*",
           "Accept-Encoding": "gzip, deflate, br",
           "Accept-Language": "en-US,en;q=0.9,pt;q=0.8",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                         "AppleWebKit/537.36 (KHTML, like Gecko) "
                         "Chrome/65.0.3325.181 Safari/537.36"
           }

r = requests.get(url, stream=True, headers=headers)

没有重定向,我也调试并查看requests.model.Response的内容,但没有成功。你知道吗

我错过了什么?我想这是关于请求的一个细节,但我不能得到它。你知道吗

这是我的测试:

url = "https://cpom.prefeitura.sp.gov.br/prestador/SituacaoCadastral/ImagemCaptcha?u=8762520"
r = requests.get(url, stream=True)

if r.status_code == 200:
    print(r.raw.headers)
    with open("/home/bruno/captcha/8762520.txt", "wb") as f:  # saving as text, since is not the png image
        for chunk in r:
            f.write(chunk)

这是下载图像的URL:https://cpom.prefeitura.sp.gov.br/prestador/SituacaoCadastral/ImagemCaptcha?u=4067913

这是带有验证码图像的站点:https://cpom.prefeitura.sp.gov.br/prestador/SituacaoCadastral

使用一个简单的GET将只得到一个json响应体,但是检查响应时您将看到二进制响应,即大约36kb大小的图像。你知道吗

编辑:包括来自restlet客户端的图像

请求: Request sample

答复: Partial response


Tags: https图像brurl二进制requestsspheaders
1条回答
网友
1楼 · 发布于 2024-04-25 01:15:19

区别在于Cookie头。Restlet默认使用现有Chrome的cookies(see docs),但是如果您将Cookie头设置为空字符串,您将看到无法获得图像。如果您希望能够从Python脚本中检索图像,则首先需要获得一个有效的cookie,请求web应用程序中的另一个有效URL(例如与您发布的表单的链接),并查看Set-Cookie(有关详细信息,请参见MDN docs)。你知道吗

相关问题 更多 >