使用python请求登录网站 [英] Login to a website using python requests

查看:107
本文介绍了使用python请求登录网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过python脚本登录网站时遇到了一些困难,以便稍后在连接后可以从中检索数据. 我认为,HTML页面中具有期望用户名和密码的形式的部分如下:

I encounter some difficulties to log on a website from a python script, in order to retrieve data from it later on, once I will be connected. I think that the part of the HTML page with the form expecting username and password is the following :

<div class="contentLogin">
        <form action="/login/loginSubmit" method="post" class="memberLogin">
    <table cellpadding="0" cellspacing="0" border="0" >
        <tr>
            <td><label class="color2">Déjà membre</label></td>
            <td>&nbsp;</td>
            <td><input type="text" value="pseudo" class="input" name="login" id="login" /></td>
            <td><input type="password" value="pass" class="input" name="pass" id="pass" /></td>
            <td><input type="submit" value="ok" class="color2 loginSubmit" /></td>
        </tr>
        <tr>
            <td colspan="3"></td>
            <td colspan="2" >
                <a href="#" class="forgotPassword color2" id="forgotPassword">Mot de passe oublié ?</a>
            </td>
        </tr>
    </table>
</form>    </div>

我想使用python语言的请求"模块来执行POST请求,该请求会将我连接到该站点. 我的代码已经包含以下命令:

I would like to use the "requests" module of python langage, to do the POST request that will connect me to the site. My code already contains the following commands :

import requests
pars = {'login': 'dva2tlse', 'pass': 'VeryStrong', 'action': 'Idunno'}
resp = requests.post("http://www.example.com", params=pars)

但是它似乎不起作用,因为我什至不知道应该在POST请求中指示WHICH动作. (我什至不知道如何使用它,因为我从未做过) 谢谢您帮助我使所有工作正常进行, 大卫

But it seems not to work, because I even do not know WHICH action should be indicated within th POST request. (I do not even know how exactly to use it, since I never done it) Thank' you to help me make all that work correctly, David

推荐答案

更改requests.post中的url值以匹配<form action>属性中给出的值.

Change the url value in requests.post to match the one given in <form action> attribute.

此外,删除pars词典中的action键.

Also, remove the action key in your pars dictionary.

pars = { 'login': 'dva2tlse', 'pass': 'VeryStrong' }
resp = requests.post("http://example.com/login/loginSubmit", params=pars)

如果您想保留登录状态以进行进一步的页面调用,可以使用requests.Session()

If you want to keep your login state for further page calls, you can use requests.Session()

s = requests.Session()
pars = { 'login': 'dva2tlse', 'pass': 'VeryStrong' }
resp = s.post("http://example.com/login/loginSubmit", params=pars)

只要继续使用s,您就可以保持登录状态.

As long as you keep using s, you will stay logged in.

这篇关于使用python请求登录网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆