繁体   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