首页 > 解决方案 > 使用 Jsoup 登录和导航

问题描述

我正在尝试使用 JSoup 登录网站,我的目标是从网站上抓取一些数据,但我在登录/导航时遇到了一些问题。

有关代码当前的外观,请参见下面的代码。

    try {
        Connection.Response response = Jsoup.connect("https://app.northpass.com/login")
                .method(Connection.Method.GET)
                .execute();

        response = Jsoup.connect("https://app.northpass.com/login")
                .data("educator[email]", "email123")
                .data("educator[password]", "password123")
                .cookies(response.cookies())
                .method(Connection.Method.POST)
                .execute();

        // Go to new page
        Document coursePage = Jsoup.connect("https://app.northpass.com/course")
                .cookies(response.cookies())
                .get();

        System.out.println(groupPage.title());

    } catch (IOException e) {
        e.printStackTrace();
    }

我也尝试过添加

.data("commit", "Log in")

.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")

没有任何成功。

我得到的错误如下:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=500, URL=https://app.northpass.com/login

根据我在其他线程上阅读的内容,人们建议使用 userAgent(如上所述,我已经尝试过)。提前感谢您的帮助。

标签: javaweb-scrapingjsoup

解决方案


如果您在浏览器中尝试登录时查看网络流量,您会看到发送了额外的数据项:authenticity_token. 这是表单中的隐藏字段。

然后,您需要从初始响应中提取它并使用 POST 请求发送它:

try {
    Connection.Response response = Jsoup.connect("https://app.northpass.com/login")
            .method(Connection.Method.GET)
            .execute();

    //I can't test this but will be something like
    //see https://jsoup.org/cookbook/extracting-data/selector-syntax
    Document document = response.parse();
    String token = document.select("input[hidden]").first().val();

    response = Jsoup.connect("https://app.northpass.com/login")
            .data("educator[email]", "email123")
            .data("educator[password]", "password123")
            .data("authenticity_token", token)
            .cookies(response.cookies())
            .method(Connection.Method.POST)
            .execute();

    // Go to new page
    Document coursePage = Jsoup.connect("https://app.northpass.com/course")
            .cookies(response.cookies())
            .get();

    System.out.println(groupPage.title());

} catch (IOException e) {
    e.printStackTrace();
}

推荐阅读