首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Python Requests模块模拟HTTP post请求?

如何使用Python Requests模块模拟HTTP post请求?
EN

Stack Overflow用户
提问于 2012-10-31 05:35:32
回答 2查看 75.8K关注 0票数 24

This是我正在尝试使用的模块,并且有一个我试图自动填写的表单。我喜欢使用请求而不是机械化的原因是因为使用机械化,我必须首先加载登录页面,然后才能填写和提交,而使用请求,我可以跳过加载阶段,直接转到POSTing消息(希望如此)。基本上,我试图让登录过程消耗尽可能少的带宽。

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

当涉及到HTTP请求和诸如此类的事情时,我是一个新手,所以任何帮助都将不胜感激。仅供参考,这是为了学校的一个项目。

编辑问题的第一部分已经回答了。我现在的问题是第二部分

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-31 05:51:41

一些示例代码:

代码语言:javascript
复制
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属性(请参见上文)。

您提供的request.session恰好有一个“记住我”,虽然我还没有尝试过(因为我不能),但这意味着它将在一段时间内发出一个cookie,以避免再次登录-- cookie保存在URL中。

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

票数 39
EN

Stack Overflow用户

发布于 2013-04-27 00:10:27

为了在请求get或post函数中使用身份验证,只需提供auth参数。如下所示:

有关更多详细信息,请参阅Requests Authentication Documentation

使用Chrome的开发人员工具,您可以检查包含您想要填写和提交的表单的html页面的元素。有关如何做到这一点的解释,请访问here。您可以找到填充post请求的数据参数所需的数据。如果您不担心验证正在访问的站点的安全证书,那么您也可以在get参数列表中指定它。

如果您的html页面包含以下用于web表单发布的元素:

代码语言:javascript
复制
<textarea id="text" class="wikitext" name="text" cols="80" rows="20">
This is where your edited text will go
</textarea>
<input type="submit" id="save" name="save" value="Submit changes">

然后,要发布到此表单的python代码如下所示:

代码语言:javascript
复制
import requests
from bs4 import BeautifulSoup

url = "http://www.someurl.com"

username = "your_username"
password = "your_password"

response = requests.get(url, auth=(username, password), verify=False)

# Getting the text of the page from the response data       
page = BeautifulSoup(response.text)

# Finding the text contained in a specific element, for instance, the 
# textarea element that contains the area where you would write a forum post
txt = page.find('textarea', id="text").string

# Finding the value of a specific attribute with name = "version" and 
# extracting the contents of the value attribute
tag = page.find('input', attrs = {'name':'version'})
ver = tag['value']

# Changing the text to whatever you want
txt = "Your text here, this will be what is written to the textarea for the post"

# construct the POST request
form_data = {
    'save' : 'Submit changes'
    'text' : txt
} 

post = requests.post(url,auth=(username, password),data=form_data,verify=False)
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13147914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档