如何使用Python模块的请求来模拟HTTP POST请求?(How to simulate HTT

2019-07-03 11:36发布

这是我尝试使用并有我想要自动填写表单模块。 我想使用了机械化的要求的原因是因为机械化,我得先加载登录页面之前,我可以填写并提交,而与采购,我可以跳过加载阶段而直接进入张贴消息(希望)。 基本上,我试图让登录过程消耗尽可能少的带宽越大越好。

我的第二个问题是,登录过程和重定向后,是否有可能无法完全下载整个页面,而是只检索页面标题? 基本上,仅在标题会告诉我,如果登陆成功与否,所以我希望尽量减少带宽使用。

我是怎样的一个小白,当谈到HTTP请求和诸如此类的东西,所以任何帮助,将不胜感激。 仅供参考,这是一所学校的项目。

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

Answer 1:

一些示例代码:

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 /镀铬/ IE工具什么(或只是查看源))。 然后找到input元件和标识所需的name属性(见上文)。

您提供的网址刚好有一个“记住我”,这虽然我没有试过(因为我不能),意味着它会发出一段时间的cookie以避免进一步的登录 - 这饼干保持在request.session

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



Answer 2:

为了使用认证中的请求得到或交功能,您只需提供auth的说法。 像这样:

response = requests.get(url, auth = ('username', 'password'))参考请求认证文档进行更详细的信息。

使用Chrome的开发者工具,你可以检查你的HTML页面中包含您想填写并提交表单的元素。 对于如何做到这一点的解释去这里 。 你可以找到你需要填充您的POST请求的数据参数数据。 如果你不担心验证您正在访问则该网站的安全证书,你还可以指定在GET参数列表。

如果你的HTML页面有这些元素用于Web表单提交:

<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代码发布到这个形式如下:

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)


文章来源: How to simulate HTTP post request using Python Requests module?