簡體   English   中英

使用 python 登錄到帶有 csrfmiddlewaretoken 驗證的網站

[英]Log in to a website with csrfmiddlewaretoken verification using python

我正在使用以下代碼通過 csrfmiddlewaretoken 驗證登錄到一個網站,但它拋出了以下錯誤:

“csrfmiddlewaretoken = HTML.find_all('input')[1]['value'] IndexError: 列表索引超出范圍”

你認為是什么問題,我是使用 python 的新手 :)

import requests
from bs4 import BeautifulSoup

request_url = 'https://text.gob.pe/accounts/login/'
with requests.session() as session:
get_url = session.get('https://text.gob.pe/accounts/login/')
HTML = BeautifulSoup(get_url.text, 'html.parser')
csrfmiddlewaretoken = HTML.find_all('input')[1]['value']

#logging in
payload = {
    'next' : '/ profile /',
    'username' : 'secret',
    'password' : 'secret',
    'next': '/ profile /',
    'csrfmiddlewaretoken': csrfmiddlewaretoken
}
headers = {
    'Referer': 'https://text.gob.pe/accounts/login/'
}
login_request = session.post(request_url,payload, headers=headers)
home_page = session.get("https://text.gob.pe/ficha/buscar/")
print(home_page.content)

沒有用戶名和密碼,很難說明如何進行。 目前你的錯誤是你沒有指定標題

headers = {
  'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'content-type': 'application/x-www-form-urlencoded',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}

url = "https://logincovid19.minsa.gob.pe/accounts/login/"
session = requests.Session()
response = session.get(url, headers=headers)
csrfmiddlewaretoken = BeautifulSoup(response.text, 'lxml').find('input', {'name': 'csrfmiddlewaretoken'}).get('value')

現在csrfmiddlewaretoken是這樣的 - eyHLYFv7HOYxglzFS9a3JDxOT38u8mrakdwhatOnkvcJJzwN9dNi6olBxJxD1HZi

我認為進一步的代碼看起來像這樣,但你需要檢查它:

user = 'YourUserNmaeHere'
password = 'UserPaswordHere'
payload = f'csrfmiddlewaretoken={csrfmiddlewaretoken}&username={user}&password={password}'
response = session.post(url, data=payload, headers=headers)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM