如何在Python请求模块中获取响应URL? [英] How to get response URL in Python requests module?

查看:227
本文介绍了如何在Python请求模块中获取响应URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm tyring to login to a website login.php using Python requests module. If the attempt is successful, the page will be redirected to index.php If not, it remains there in login.php.

我能够使用mechanize模块执行相同的操作.

I was able to do the same with mechanize module.

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模块做同样的事情?

My question is how to do the same with requests module?

我正在尝试不同的方法在这里,但是它们都不起作用.

I was trying different approach here, but none of them work.

推荐答案

我从

I've took the code from your question and modified it:

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

您可以肯定这是确定的,因为它是中记录的源代码.我所做的只是打开Response类的定义.

You can know it's a sure thing because it's documented in the source code. All I've done is opened the definition of the Response class.

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

Now, back to your original question.

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

Python requests module to verify if HTTP login is successful or not

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

It depends on whether the website is properly implemented.

发送表单时,任何网站都会通过HTTP响应来回复您,该HTTP响应包含状态码.正确实施的网站会根据您发送的内容返回不同的状态代码. 这是它们的列表.如果一切正常,响应的状态码将为200:

When you send a form, any website replies to you with an HTTP response, which contains a status code. A properly implemented website returns different status codes depending on the stuff you've sent. Here's a list of them. If everything is honky-dory, the status code of the response will be 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(请参见上面的列表).现在,如果网站实施不正确,无论如何都会以200响应,您将不得不基于其他因素(例如response.contentresponse.url)来猜测登录是否成功.

If the user entered the wrong credentials, the status code of the response will be 401 (see the list above). Now, if a website is not implemented properly, it will respond with 200 anyway and you'll have to guess whether the login is successful based on other things, such as response.content and response.url.

这篇关于如何在Python请求模块中获取响应URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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