小编典典

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

python

我正在尝试使用Python中的“请求”模块发布一个登录网站的请求,但它实际上无法正常工作。我是新来的…所以我不知道是否应该制作我的用户名和密码cookie或我发现的某种HTTP授权内容(??)。

from pyquery import PyQuery
import requests

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

所以现在,我认为我应该使用“发布”和cookie。

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”上;如果登录不正确,则应显示为“首页”。

如果你可以向我解释一些有关请求和cookie的事情,并帮助我解决这个问题,我将不胜感激。

…它仍然没有真正起作用。好的…所以这是登录之前主页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”

第二次编辑:

我希望能够长时间保持登录状态,每当我请求该域下的页面时,我都希望内容显示出来就像我已登录一样。


阅读 533

收藏
2020-02-14

共2个答案

小编典典

如果你想要的信息在页面上,登录后将立即定向到该页面。
让我们改为调用你的ck变量payload,例如在python-requests文档中:

payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)
2020-02-14
小编典典

首先,就像Marcus一样,检查登录表单的源以获取三项信息-表单发布到的URL以及用户名和密码字段的名称属性。在他的示例中,它们是inUserNameinUserPass

一旦知道了这一点,就可以使用requests.Session()实例向登录URL发出发布请求,并将登录详细信息作为有效内容。从会话实例发出请求本质上与正常使用请求相同,它只是增加了持久性,允许你存储和使用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...
2020-02-14