爲了內的請求得到或交功能,您只需提供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