Jsoup发布和Cookie

52

我正在尝试使用jsoup登录一个网站并抓取信息,但是遇到了问题。我可以成功登录并从index.php创建文档,但我无法获取该网站上的其他页面。我知道需要在提交后设置cookie,并在尝试打开站点的另一页时加载它。但我该如何做呢?以下代码允许我登录并获取index.php。

Document doc = Jsoup.connect("http://www.example.com/login.php")
               .data("username", "myUsername", 
                     "password", "myPassword")
               .post();

我知道可以使用apache httpclient来完成这个任务,但我不想这么做。


这段代码对你来说能够用于登录并从网站上爬取信息吗?因为在我的情况下它没有起作用。 - lucifer
你可以在这里查看我的代码:https://dev59.com/4ofca4cB1Zd3GeqPfS6w?noredirect=1#comment44615745_28110219 - lucifer
6个回答

111

当您登录网站时,它可能会设置一个授权的会话cookie,并需要在后续请求中发送该cookie以维护会话。

您可以通过以下方式获取该cookie:

Connection.Response res = Jsoup.connect("http://www.example.com/login.php")
    .data("username", "myUsername", "password", "myPassword")
    .method(Method.POST)
    .execute();

Document doc = res.parse();
String sessionId = res.cookie("SESSIONID"); // you will need to check what the right cookie name is

然后在下一个请求中发送它,例如:

Document doc2 = Jsoup.connect("http://www.example.com/otherPage")
    .cookie("SESSIONID", sessionId)
    .get();

1
但是如何获取 HttpOnly cookies? - iAmLearning
请明确如何检查“// you will need to check what the right cookie name is” - vikramvi
res.cookies(); 给了我 {pgv=2, alp=VROL, aa=364476%7C813843989%7C196006251, arl=205118481, currency=INR, magnitude=LC, PERMA-ALERT=0, alo=deleted},但是当将其作为参数传递到另一个 URL 时,它并没有全部被记录下来。 - vikramvi
您的解决方案无效,请检查https://stackoverflow.com/questions/73572751/jsoup-login-cookies-are-not-working-with-sub-pages-but-only-with-home-page。 - vikramvi
根据 https://dev59.com/m5Pfa4cB1Zd3GeqPCmQi,我得到了2组cookie,那么我应该在子页面中使用哪一个? {PHPSESSID=iulmm77ir2ckid32euviubb0ad, currency=INR, magnitude=LC, ad=d8eedce649453f70f2ae83d02ef48a32426bfc9d, wec=291312787, nobtlgn=626283907, pgv=1}{pgv=2, alp=VROL, aa=364476%7C244856479%7C600763075, arl=847554676, currency=INR, magnitude=LC, PERMA-ALERT=0, alo=deleted} - vikramvi

19
//This will get you the response.
Response res = Jsoup
    .connect("loginPageUrl")
    .data("loginField", "login@login.com", "passField", "pass1234")
    .method(Method.POST)
    .execute();

//This will get you cookies
Map<String, String> loginCookies = res.cookies();

//And this is the easiest way I've found to remain in session
Document doc = Jsoup.connect("urlYouNeedToBeLoggedInToAccess")
      .cookies(loginCookies)
      .get();

现在它不能工作。我正在努力登录并爬取Facebook帐户。现在,Facebook引入了一些更多的参数。lsd:AVptuGRS email:*** pass:*** default_persistent:0 timezone:-120 lgnrnd:043627_eQnN lgnjs:1383914188 locale:en_US 请查看此链接:https://dev59.com/U3jZa4cB1Zd3GeqPjebo - Vishwajit R. Shinde
嘿,伙计,我按照你说的做了。但是我无法获取“需要登录才能访问的URL”的网页。请回答我。 - Kumaresan Perumal
对我不起作用。org.jsoup.HttpStatusException: HTTP错误获取URL。状态=400, - Avinash
你的解决方案不起作用,能否请您检查一下 https://stackoverflow.com/questions/73572751/jsoup-login-cookies-are-not-working-with-sub-pages-but-only-with-home-page - vikramvi

1

代码所在位置:

Document doc = Jsoup.connect("urlYouNeedToBeLoggedInToAccess").cookies().get(); 

我遇到了困难,直到我把它改成:
Document doc = Jsoup.connect("urlYouNeedToBeLoggedInToAccess").cookies(cookies).get();

现在它运行得非常完美。


0

以下是您可以尝试的...

import org.jsoup.Connection;


Connection.Response res = null;
    try {
        res = Jsoup
                .connect("http://www.example.com/login.php")
                .data("username", "your login id", "password", "your password")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

现在保存所有的 cookie,然后向您想要的其他页面发出请求。
//Store Cookies
cookies = res.cookies();

向另一个页面发出请求。

try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}

如果需要进一步的帮助,请提出。


你的解决方案不起作用,请检查 https://stackoverflow.com/questions/73572751/jsoup-login-cookies-are-not-working-with-sub-pages-but-only-with-home-page。 - vikramvi

0
为什么要重新连接? 如果有任何cookie可以避免403状态,我会这样做。
                Document doc = null;
                int statusCode = -1;
                String statusMessage = null;
                String strHTML = null;
        
                try {
    // connect one time.                
                    Connection con = Jsoup.connect(urlString);
    // get response.
                    Connection.Response res = con.execute();        
    // get cookies
                    Map<String, String> loginCookies = res.cookies();

    // print cookie content and status message
                    if (loginCookies != null) {
                        for (Map.Entry<String, String> entry : loginCookies.entrySet()) {
                            System.out.println(entry.getKey() + ":" + entry.getValue().toString() + "\n");
                        }
                    }
        
                    statusCode = res.statusCode();
                    statusMessage = res.statusMessage();
                    System.out.print("Status CODE\n" + statusCode + "\n\n");
                    System.out.print("Status Message\n" + statusMessage + "\n\n");
        
    // set login cookies to connection here
                    con.cookies(loginCookies).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0");
        
    // now do whatever you want, get document for example
                    doc = con.get();
    // get HTML
                    strHTML = doc.head().html();

                } catch (org.jsoup.HttpStatusException hse) {
                    hse.printStackTrace();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

0
Connection.Response res = Jsoup.connect("http://www.example.com/login.php")
    .data("username", "myUsername")
    .data("password", "myPassword")
    .method(Connection.Method.POST)
    .execute();
//Connecting to the server with login details
Document doc = res.parse();
//This will give the redirected file
Map<String,String> cooki=res.cookies();
//This gives the cookies stored into cooki
Document docs= Jsoup.connect("http://www.example.com/otherPage")
    .cookies(cooki)
    .get();
//This gives the data of the required website

3
欢迎来到SO。在发布回答之前,请阅读 how-to-answer。那个代码块是什么意思? - fjsv
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - β.εηοιτ.βε

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接