为了在请求 get 或 post 函数中使用身份验证,您只需提供auth
参数。像这样:
response = requests.get(url, auth = ('username', 'password'))
有关更多详细信息,请参阅请求身份验证文档。
使用 Chrome 的开发人员工具,您可以检查包含您要填写和提交的表单的 html 页面的元素。有关如何完成此操作的说明,请访问此处。您可以找到填充发布请求的数据参数所需的数据。如果您不担心验证您正在访问的站点的安全证书,那么您也可以在 get 参数列表中指定它。
如果您的 html 页面有这些元素可用于您的网络表单发布:
<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)