リクエストの get または post 関数内で認証を使用するには、auth
引数を指定するだけです。このような:
response = requests.get(url, auth = ('username', 'password'))
詳細については、リクエスト認証のドキュメントを参照してください。
Chrome の開発者ツールを使用して、入力して送信するフォームを含む HTML ページの要素を調べることができます。これがどのように行われるかの説明については、こちらを参照してください。投稿リクエストのデータ引数に入力する必要があるデータを見つけることができます。アクセスしているサイトのセキュリティ証明書を検証することを心配していない場合は、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)