如何使用 Python Requests 模块模拟 HTTP post 请求? [英] How to simulate HTTP post request using Python Requests module?

查看:32
本文介绍了如何使用 Python Requests 模块模拟 HTTP post 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个是我正在尝试使用的模块,并且有一个我正在尝试自动填写的表格.我想在 Mechanize 上使用 Requests 的原因是因为使用 Mechanize,我必须先加载登录页面,然后才能填写并提交,而使用 Requests,我可以跳过加载阶段并直接发布消息(希望).基本上,我试图让登录过程消耗尽可能少的带宽.

This is the module that I'm trying to use and there is a form I'm trying to fill automatically. The reason I'd like to use Requests over Mechanize is because with Mechanize, I have to load the login page first before I can fill it out and submit, whereas with Requests, I can skip the loading stage and go straight to POSTing the message (hopefully). Basically, I'm trying to make the login process consume as little bandwidth as possible.

我的第二个问题是,在登录过程和重定向之后,是否可以不完全下载整个页面,而只检索页面标题?基本上,只有标题会告诉我登录是否成功,所以我想尽量减少带宽使用.

My second question is, after the login process and the redirection, is it possible to not fully download the whole page, but to only retrieve the page title? Basically, the title alone will tell me if the login succeeded or not, so I want to minimize bandwidth usage.

当涉及到 HTTP 请求等问题时,我是个菜鸟,因此我们将不胜感激.仅供参考,这是一个学校项目.

I'm kind of a noob when it comes to HTTP requests and whatnot, so any help would be appreciated. FYI, this is for a school project.

edit 问题的第一部分已经回答.我现在的问题是第二部分

edit The first part of the question has been answered. My question now is for the second part

推荐答案

一些示例代码:

import requests

URL = 'https://www.yourlibrary.ca/account/index.cfm'
payload = {
    'barcode': 'your user name/login',
    'telephone_primary': 'your password',
    'persistent': '1'  # remember me
}

session = requests.session()
r = requests.post(URL, data=payload)
print r.cookies

第一步是查看您的源页面并确定正在提交的 form 元素(使用 Firebug/Chrome/IE 工具,无论(或仅查看源)).然后找到 input 元素并确定所需的 name 属性(见上文).

The first step is to look at your source page and identify the form element that is being submitted (use Firebug/Chrome/IE tools whatever (or just looking at the source)). Then find the input elements and identify the required name attributes (see above).

您提供的 URL 恰好有一个记住我",虽然我没有尝试过(因为我不能),但这意味着它会在一段时间内发出 cookie 以避免进一步登录——即cookie 保存在 request.session 中.

The URL you provided happens to have a "Remember Me", which although I haven't tried (because I can't), implies it'll issue a cookie for a period of time to avoid further logins -- that cookies is kept in the request.session.

然后只需使用 session.get(someurl, ...) 来检索页面等...

Then just use session.get(someurl, ...) to retrieve pages etc...

这篇关于如何使用 Python Requests 模块模拟 HTTP post 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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