如何使用Python的请求模块“登录”网站?

2024-04-26 10:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图发布一个请求,使用Python中的Requests模块登录到一个网站,但它并不真正起作用。我是新来的…所以我不知道我是否应该做我的用户名和密码cookies或某种类型的HTTP授权我发现的东西(??)。

from pyquery import PyQuery
import requests

url = 'http://www.locationary.com/home/index2.jsp'

所以现在,我想我应该用“post”和cookies。。。。

ck = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}

r = requests.post(url, cookies=ck)

content = r.text

q = PyQuery(content)

title = q("title").text()

print title

我觉得我做错了曲奇…我不知道。

如果登录不正确,主页的标题应该显示为“Locationary.com”,如果是,则应该显示为“主页”

如果你能向我解释一些关于请求和饼干的事情,并帮助我解决这个问题,我将非常感谢。:天

谢谢。

……它还没有真正起作用。好吧…这就是你登录前的主页HTML所说的:

</td><td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_email.gif">    </td>
<td><input class="Data_Entry_Field_Login" type="text" name="inUserName" id="inUserName"  size="25"></td>
<td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_password.gif"> </td>
<td><input  class="Data_Entry_Field_Login"  type="password" name="inUserPass"     id="inUserPass"></td>

所以我认为我做得对,但是输出仍然是“Locationary.com”

第二次编辑:

我希望能够保持登录很长一段时间,每当我在该域下请求一个页面时,我希望内容显示为我已登录。


Tags: textimportcomhttpimgtitlewww主页
3条回答

我知道你已经找到了另一个解决方案,但对于像我这样发现这个问题的人来说,寻找同样的问题,可以通过以下请求来实现:

首先,正如Marcus所做的那样,检查登录表单的来源以获得三条信息:表单发布到的url,用户名和密码字段的name属性。在他的例子中,它们是inUserName和inUserPass。

一旦你得到了这个,你就可以使用一个requests.Session()实例向登录url发出post请求,并将你的登录详细信息作为一个有效负载。从会话实例发出请求本质上与正常使用请求相同,它只是添加持久性,允许您存储和使用cookie等

假设您的登录尝试成功,您可以简单地使用会话实例向站点发出进一步的请求。标识您的cookie将用于授权请求。

示例

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'inUserName': 'username',
    'inUserPass': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post('LOGIN_URL', data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    r = s.get('A protected web page url')
    print r.text
        # etc...

让我试着让它变得简单,假设站点的URL是http://example.com/,假设您需要通过填写用户名和密码进行注册,所以我们现在转到登录页面说http://example.com/login.php,查看它的源代码并搜索操作URL,它将以类似于

 <form name="loginform" method="post" action="userinfo.php">

现在使用userinfo.php生成绝对URL,它将是http://example.com/userinfo.php,现在运行一个简单的python脚本

import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
          'password': 'pass'}

r = requests.post(url, data=values)
print r.content

我希望有一天这能帮助别人。

如果您想要的信息在登录后立即指向的页面上

让我们改为调用ck变量payload,就像在python-requests文档中一样:

payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)

否则

请参阅下面的https://stackoverflow.com/a/17633072/111362

相关问题 更多 >