python请求 - 403禁止

时间:2015-01-15 15:12:29

标签: python python-requests

我有这个

payload = {'from':'me', 'lang':lang, 'url':csv_url}
headers = {
   'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
}

api_url = 'http://dev.mypage.com/app/import/'
sent = requests.get(api_url , params=payload, headers=headers)

我一直在403。我很期待this requests docs

我做错了什么?

更新

该网址仅接受登录用户。如何使用请求登录?

1 个答案:

答案 0 :(得分:1)

这是通常使用Session对象完成的方式:

# start new session to persist data between requests
session = requests.Session()

# log in session
response = session.post(
    'http://dev.mypage.com/login/',
    data={'user':'username', 'password':'12345'}
)

# make sure log in was successful
if not 200 <= response.status_code < 300:
    raise Exception("Error while logging in, code: %d" % response. status_code)

# ... use session object to make logged-in requests, your example:
api_url = 'http://dev.mypage.com/app/import/'
sent = session.get(api_url , params=payload, headers=headers)

您显然应该根据您的使用情况进行调整。

需要会话的原因是HTTP协议没有会话的概念,因此会话通过 over HTTP实现。