简体   繁体   中英

PYTHON: requests and response 401

I have a little problem with authentication. I am writting a script, which is getting login and password from user(input from keyboard) and then I want to get some data from the website(http not https), but every time I run the script the response is 401.I read some similar posts from stack and I tried this solutions:

Solution 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()

Solution 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)

Solution 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())'

I don't know how to solve this problem. Can somebody give me some link or tip ?

Have you tried the Basic Authentication example from requests?

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

Can I know what type of authentication on the website?

this is an official Basic Auth example ( 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)

To use api with authentication, we need to have token_id or app_id that will provide the access for our request. Below is an example how we can formulate the url and get the response: strong text

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM