如何在Python请求模块中获取响应URL?

时间:2019-10-06 02:46:40

标签: python python-3.x authentication python-requests mechanize

我打算使用Python请求模块登录网站login.php。 如果尝试成功,页面将被重定向到index.php 如果没有,它将保留在login.php中。

我可以使用mechanize模块来做同样的事情。

import mechanize
b = mechanize.Browser()
url = 'http://localhost/test/login.php'
response = b.open(url)
b.select_form(nr=0)
b.form['username'] = 'admin'
b.form['password'] = 'wrongpwd'
b.method = 'post'
response = b.submit()
print(response.geturl())
if response.geturl() == url:
    print('Failed')
else:
    print('OK')

如果登录名/密码正确

user@linux:~$ python script.py 
http://localhost/test/index.php
OK
user@linux:~$ 

如果登录名/密码错误

user@linux:~$ python script.py 
http://localhost/test/login.php
Failed
user@linux:~$ 

我的问题是如何使用requests模块来做同样的事情?

我尝试使用不同的方法here,但是它们都不起作用。

1 个答案:

答案 0 :(得分:1)

我已经从your question中获取了代码并对其进行了修改:

$query_edit = 'SELECT * FROM tbl_post WHERE id="' . $editpost . '"';

您可以肯定这是肯定的,因为它是documented in the source code。我所做的只是打开import requests url = 'http://localhost/test/login.php' values = {'username': 'admin', 'password': 'wrongpwd'} r = requests.post(url, data=values) print(r.url) # prints the final url of the response 类的定义。

现在,回到您的原始问题。

  

Python请求模块来验证HTTP登录是否成功

这取决于网站是否正确实施。

发送表单时,任何网站都会通过HTTP响应来回复您,其中包含状态码。正确实施的网站会根据您发送的内容返回不同的状态代码。 Here's a list of them。如果一切正常,则响应的状态码将为Response

200

如果用户输入了错误的凭据,则响应的状态码将为import requests url = 'http://localhost/test/login.php' values = {'username': 'admin', 'password': 'wrongpwd'} r = requests.post(url, data=values) print(r.status_code == 200) # prints True (请参见上面的列表)。现在,如果某个网站的实施不正确,无论如何它都会以401进行响应,您将不得不基于其他原因来猜测登录是否成功,例如200response.content