PYTHON:请求和响应401

时间:2018-08-20 07:31:51

标签: python python-3.x

我在身份验证方面有点问题。我正在编写一个脚本,该脚本从用户那里获取登录名和密码(从键盘输入),然后我想从网站(http不是https)获取一些数据,但是每次我运行该脚本时,响应都是401。来自堆栈的一些类似帖子,我尝试了以下解决方案:

解决方案1 ​​

c = HTTPConnection("somewebsite")
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  userAndPass }
c.request('GET', '/', headers=headers)
res = c.getresponse()
data = res.read()

解决方案2

with requests.Session() as c:
    url = 'somewebsite'
    USERNAME = 'username'
    PASSWORD = 'password'
    c.get(url)
    login_data = dict(username = USERNAME, password = PASSWORD)
    c.post(url,data = login_data)
    page = c.get('somewebsite', headers = {"Referer": "somwebsite"})
    print(page)

解决方案3

www = 'somewebsite'
value ={'filter':'somefilter'}
data = urllib.parse.urlencode(value)
data=data.encode('utf-8')
req = urllib.request.Request(www,data)
resp = urllib.request.urlopen(req)
respData = resp.read()
print(respData)
x = urllib.request.urlopen(www,"username","password")
print(x.read())'

我不知道如何解决这个问题。有人可以给我一些联系或提示吗?

3 个答案:

答案 0 :(得分:1)

您是否尝试过来自请求的Basic Authentication示例?

>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>

答案 1 :(得分:1)

我可以知道网站上的身份验证类型吗?

这是官方的基本身份验证示例(http://docs.python-requests.org/en/master/user/advanced/#http-verbs

from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')

r = requests.post(url=url, data=body, auth=auth)
print(r.status_code)

答案 2 :(得分:0)

要使用api进行身份验证,我们需要有token_id或app_id,它们将为我们的请求提供访问权限。下面是一个示例,我们如何制定网址并获得响应: strong文字

import requests
city = input()
api_call = "http://api.openweathermap.org/data/2.5/weather?"
app_id = "892d5406f4811786e2b80a823c78f466"
req_url = api_call + "q=" + city + "&appid=" + app_id
response = requests.get(req_url)
data = response.json()
if (data["cod"] == 200):
    hum = data["main"]["humidity"]
    print("Humidity is % d " %(hum))
elif data["cod"] != 200:
    print("Error occurred : " ,data["cod"], data["message"])