从Python

时间:2015-06-07 06:32:02

标签: python python-requests

我正在尝试从命令行登录www.codeforces.com/enter,但是在每次尝试时,都会因[403]响应错误而失败。代码原型如下:

import requests
import getpass

base = "http://codeforces.com"
cf_enter = "{base}/{login}".format(base=base, login="enter")

cliente = requests.session()
r = cliente.get(cf_enter)

user = raw_input('User:')
password = getpass.getpass('Password:')

login_data = {
    'action': 'enter',
    'handle': user,
    'password': password,
}
r = cliente.post(cf_enter, data=login_data, headers=dict(Referer=cf_enter))
print r

顺便说一下,当我登录网站时分析包时,我在POST之前/之后引用了以下cookie:'csrf_token',“JSESSIONID”,“39ce7”,并且有效负载有'handle'(用户名)和'密码'。

UPDATE1

在第一条评论之后,我更改了代码。它适用于登录,并接收[200]响应,但我想提交一个代码,例如,“http://codeforces.com/contest/4/submit

import requests
import getpass
from bs4 import BeautifulSoup as bs

base = "http://codeforces.com"
cf_enter = "{base}/{login}".format(base=base, login="enter")

cliente = requests.session()
r = cliente.get(cf_enter)
html = r.content
soup = bs(html)
head = soup.head
meta = head.findChildren('meta')
csrf_token = [
    m for m in meta if 'name' in m.attrs and m['name'] == 'X-Csrf-Token']
csrf_token = csrf_token[0]["content"]

print csrf_token # it's working, :)

user = raw_input('User:')
password = getpass.getpass('Password:')

login_data = {
    'csrf_token': csrf_token,
    'action': 'enter',
    'handle': user,
    'password': password,
}

headers = {
    'Referer': cf_enter,
    'User-agent': 'Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'
}

r = cliente.post(cf_enter, data=login_data, headers=headers)
if r.status_code != 200:
    print 'fail to connect'

type_contest = "contest"
contest_id = '4'
url_submit = "{base}/{type}/{id}/submit".format(
    base=base, type=type_contest, id=contest_id)
print url_submit

# url_submit = url_submit +'?csrf_token={0}'.format(csrf_token)
r = cliente.get(url_submit, headers=headers)
if r.status_code != 200:
    print 'fail to connect', url_submit
else:
    print '[200] ', url_submit


parts = {
    "csrf_token":            csrf_token,
    "action":                "submitSolutionFormSubmitted",
    "contestId": '4',
    "submittedProblemIndex": 'A',
    "source":                open('A.py', "rb"),
    "programTypeId":         '7',
    "sourceFile":            "",
    "_tta":                  "834",
    'handle': user,
    'password': password
}

r = cliente.post(url_submit, files=parts, headers=headers)
print r  # response: [403]
print r.cookies # here, there's nothing , hug?

任何建议使其有效(?)

0 个答案:

没有答案