授权问题

时间:2014-01-28 12:19:15

标签: python request authorization

我在python中遇到授权问题。我想自动进入网站,但我不能。我使用了很多库:Grab,urlib2,请求,但我从未输入( 为了检查自己,我输入pege帐户数据 这是真实的网站,登录名和密码

URL="http://pin-im.com/accounts/login/"
LOGIN="testuser"
PASSWORD="test12345user"

urlib2:

def authorization():
import urllib2

gh_url = 'http://pin-im.com/accounts/login/'
gh_user= 'testuser'
gh_pass = 'test12345user'

req = urllib2.Request(gh_url)

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, gh_user, gh_pass)

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

urllib2.install_opener(opener)

handler = urllib2.urlopen(req)

抓斗:

def autorization():
g = Grab()
g.setup(post={'username':'testuser', 'Password':'test12345user', 'act': 'submit'})
g.go("http://pin-im.com/accounts/login/")
g.go("http://pin-im.com/user/my-profile/")
print g.response.code

请求(我使用Request Lib中的所有方法进行授权,其中之一):

from requests.auth import HTTPBasicAuth
requests.get('http://pin-im.com/accounts/login/', auth=HTTPBasicAuth('testuser', 'test12345user'))
r. get("http://pin-im.com/user/my-profile/")
r.status_code

我很绝望,你能帮我登录这个网站吗?我做错了什么?

2 个答案:

答案 0 :(得分:0)

userData = "Basic " + ("testuser:test12345user").encode("base64").rstrip()
req = urllib2.Request('http://pin-im.com/accounts/login')
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', userData)
res = urllib2.urlopen(req)

答案 1 :(得分:0)

此网站使用CSRF protection,因此您应该获取csrftoken cookie并根据您的请求将其发回服务器:

import Cookie
from urllib import urlencode

import httplib2


URL="http://pin-im.com/accounts/login/"
LOGIN="testuser"
PASSWORD="test12345user"

http = httplib2.Http()

response, _ = http.request(URL)

cookies = Cookie.BaseCookie()
cookies.load(response["set-cookie"])
csrftoken = cookies["csrftoken"].value

headers = {'Content-type': 'application/x-www-form-urlencoded'}
headers['Cookie'] = response['set-cookie']

data = {
    "csrfmiddlewaretoken": csrftoken,
    "username":LOGIN,
    "password": PASSWORD
}

response, _ = http.request(URL, "POST", headers=headers, body=urlencode(data))

response, content = http.request(
    "http://pin-im.com/user/my-profile/",
    "GET",
    headers={'Cookie': response['set-cookie']}
)
print response, content