首页 > 解决方案 > 如何使用 python 请求登录:一个棘手的案例

问题描述

我正在尝试访问我的学校提供​​的网站,以便自动检查是否已发布某些内容(例如标记、新闻等)。

我分析了页面的 html 代码并搜索了所有输入标签(甚至是隐藏标签)并将它们放入字典中。我写了这段代码:

import requests, lxml.html
from bs4 import BeautifulSoup as bs

login_url = "https://www.portaleargo.it/argoweb/famiglia/common/login_form2.jsp"
whenloggedin_url = "https://www.portaleargo.it/argoweb/famiglia/index.jsf#"

def try_conn(sch_code, user, password):

with requests.Session() as s:

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
    site = s.get(login_url, headers = headers)
    bs_content = bs(site.content, "html.parser")
    token = bs_content.find("input", {"id":"cod_utente"})["value"]
    login_data = {
        "codice_scuola":sch_code,
        "utente":user,
        "j_password":password,
        "cod_utente":token,
    }

    login = s.post(login_url, data = login_data)

    #Proof that it logged in correctly

    if login.url == whenloggedin_url:

        return True

    return False

该函数返回 False。我还尝试打印 login.status_code (它返回 200)。我真的不能说为什么这不起作用。我应该怎么办?

标签: python-requests

解决方案


我认为这应该有效。

import requests

post_url= "https://www.portaleargo.it/argoweb/famiglia/common/j_security_check"
login_url = "https://www.portaleargo.it/argoweb/famiglia/common/login_form2.jsp"
whenloggedin_url = "https://www.portaleargo.it/argoweb/famiglia/index.jsf#"

def try_conn(sch_code, user, password):

    with requests.Session() as s:

        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
        site = s.get(login_url, headers = headers)
        login_data = {
            "udente":user,
            "j_password":password,
            "j_username":user+"#"+sch_code,
            "submit":"Entra",
        }

        login = s.post(post_url, data = login_data)

        #Proof that it logged in correctly

        if login.url == whenloggedin_url:

            return True

        return False

推荐阅读