简体   繁体   English

成功登录JSoup后无法解析网站

[英]Unable to parse website after successful log in JSoup

I successfully log into website using JSoup library, store the cookies so that i can use them for the second document where access is required. 我使用JSoup库成功登录了网站,存储了cookie,以便在需要访问的第二个文档中使用它们。 However the second document parses the data as if i am not logged in. 但是第二个文档将解析数据,好像我没有登录。

Here is the code: 这是代码:

public class Main {

public static void main(String[] args) throws Exception {

    Map<String, String> loginCookies = null;


     Connection.Response loginForm = Jsoup.connect("login page")
             .method(Connection.Method.GET)
             .execute();

     loginCookies = loginForm.cookies();

     Document document = Jsoup.connect("login page")
             .data("cookieexists", "false")
             .data("username", "user")
             .data("password", "pass")
             .data("loginbtn", "Log in")
             .cookies(loginCookies)
             .post();


    Document document2 = Jsoup.connect("Page with access required")
        .cookies(loginCookies)
        .get();

    System.out.println(document2);
}

} }

What can be wrong with this code? 此代码有什么问题?

You should store and reuse cookies which contain information about your session, which means you need to store them from server response which you get after passing your credentials, not just from empty form. 您应该存储和重复使用包含有关会话信息的cookie,这意味着您需要从传递凭据后获得的服务器响应中存储它们,而不仅仅是从空表单中获取。

So try with 所以尝试

Connection.Response loginForm = Jsoup.connect("login page")
        .data("cookieexists", "false")
        .data("username", "user")
        .data("password", "pass")
        .data("loginbtn", "Log in")
        //.cookies(loginCookies)
        .method(Connection.Method.POST)
        .execute();

//here `loginForm` connected to server with your credentials
//and server returned response with cookies containing informations
//required to continue session so you should store them
//and reuse to access farther pages
Map<String, String> loginCookies  = loginForm.cookies();

Document document2 = Jsoup.connect("Page with access required")
        .cookies(loginCookies)
        .get();

System.out.println(document2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM