python request post_Python:如何使用request模块来POST表单?

我正在尝试使用Python和RequestLibrary登录一个网站,以便进行一些抓取,我正在尝试以下内容(这是不起作用的):import requests

headers = {'User-Agent': 'Mozilla/5.0'}

payload = {'username':'niceusername','password':'123456'}

In [12]: r = requests.post('https://admin.example.com/login.php',headers=headers,data=payload)

但是没有,得到一个重定向到登录页面。我是否需要打开一个Sesson?我需要加载cookie吗?In [13]: r.headers

Out[13]: CaseInsensitiveDict({'content-encoding': 'gzip', 'transfer-encoding': 'chunked',

'set-cookie': 'PHPSESSID=v233mnt4malhed55lrpc5bp8o1; path=/',

'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'vary': 'Accept-Encoding', 'server': 'nginx',

'connection': 'keep-alive', 'pragma': 'no-cache',

'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',

'date': 'Tue, 24 Dec 2013 10:50:44 GMT', 'content-type': 'text/html'})

In [14]: r.cookies

Out[14]: <[Cookie(version=0, name='PHPSESSID',

value='v233mnt4malhed55lrpc5bp8o1', port=None, port_specified=False, domain='admin.example.com',

domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False,

expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>

我找到了答案:import requests

headers = {'User-Agent': 'Mozilla/5.0'}

payload = {'username':'usr','pass':'123'}

link = 'https://admin.example.com/login.php'

session = requests.Session()

resp = session.get(link,headers=headers)

# did this for first to get the cookies from the page, stored them with next line:

cookies = requests.utils.cookiejar_from_dict(requests.utils.dict_from_cookiejar(session.cookies))

resp = session.post(link,headers=headers,data=payload,cookies =cookies)

#used firebug to check POST data, password, was actually 'pass', under 'net' in param.

#and to move forward from here after is:

session.get(link)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值