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

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

问题描述

是我正在尝试使用的模块,并且有一个表格我正在尝试自动填写.我想在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 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发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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