Python从url保存验证码图像?错误401

时间:2016-09-18 20:13:55

标签: python python-requests

我有问题将验证码保存为png。 这是我到目前为止的代码

import requests
url_login = "https://www.hackthis.co.uk/?login"
r_login = requests.post(url_login, {'username': 'darkcyber', 'password': 'secr3tp4s5'})
print r_login.status_code
if "Invalid login details" in r_login.text:
        print "Failed to login"
else:
        print "Login success"
url_captcha = "https://www.hackthis.co.uk/levels/extras/captcha1.php"
r_captcha = requests.get(url_captcha)
#print r_captcha.status_code << 401 instead 200
#whats next?

1 个答案:

答案 0 :(得分:4)

您需要下载图片并将其另存为本地新文件。

以下是示例代码:

import requests

r = requests.get('http://url.com/captcha.php')

f = open('yourcaptcha.png', 'wb')
f.write(r.content)
f.close()

发表评论后更新:

import requests
url_login = "https://www.hackthis.co.uk/?login"

r_login = requests.post(url_login, {'username': 'darkcyber', 'password': 'secr3tp4s5'})

if "Invalid login details" in r_login.text:
        print "Failed to login"
else:
        print "Login success"

url_captcha = "https://www.hackthis.co.uk/levels/extras/captcha1.php"
r_captcha = requests.get(url_captcha, cookies=r_login.history[0].cookies)

print r_captcha.status_code

f = open('yourcaptcha.png', 'wb')
f.write(r_captcha.content)
f.close()