Python 请求响应与 chrome 响应不同



我需要从特定网站下载大约 100 张验证码图像。 我的代码总结为:

1-下载页面

2-搜索验证码图像URL(使用re(并下载

3- :(下载的图像与我在浏览器中看到的图像不同。我想我需要设置的会话或请求(获取或发布(中有一个参数,但我还没有。

import requests
import re
import time
s = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
#download this page and look for the url of the captcha image
page = s.get('http://www.rrk.ir/News/ShowOldNews.aspx?Code=1', headers=headers)
result = re.search('img id="imgCaptcha" src="..(.*)"', page.content.decode('utf-8'))
img_url = 'http://www.rrk.ir' + result.group(1).split('"')[0]
print(img_url)
#download the image and save it to a file
img = s.get(img_url, headers=headers)
img_file_name =  './a'  + '.jpg'
with open(img_file_name, 'wb') as fout:
fout.write(img.content)
s.close()
#:( the downloaded file is different from what I see in Chrome.

如何找出我缺少的设置?

更新1:按照建议,添加了自定义标头,但没有帮助。

现在我正在努力解决类似的授权问题。 如果您有类似的问题,您需要关闭 Requests(allow_redirects=False( 中的自动重定向,并检查浏览器开发人员工具中是否存在级联请求 - 也许第一个请求会导致重定向,在 data/json 新有效负载中生成其他参数,或创建新的标头/cookie。

s = requests.Session()
resp = s.get(url_here, headers=headers, allow_redirects=False)
if resp.status_code == 302:
print('Redirect!', resp.headers. resp.cookies, sep="n")

哎呀饼干和响应标题! 您也可以使用:

print(resp.history)

最新更新