为了内的请求得到或交功能,您只需提供auth
参数使用身份验证。像这样:
response = requests.get(url, auth = ('username', 'password'))
有关更多详细信息,请参阅请求Authentication Documentation。
使用Chrome的开发者工具,你可以检查你的HTML页面中包含您想填写并提交表单的元素。有关如何完成的说明,请参阅here。你可以找到你需要的数据来填充你的发布请求的数据参数。如果您不担心验证正在访问的站点的安全证书,则还可以在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)
您可以使用Chrome检查员查看哪些值传递到由浏览器创建的发布请求中,然后从那里开始。 – bossylobster