【问题标题】:jsoup posting and cookiejsoup 发布和 cookie
【发布时间】:2011-09-19 22:49:15
【问题描述】:

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

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

我知道我可以使用 apache httpclient 来执行此操作,但我不想这样做。

【问题讨论】:

标签: java screen-scraping jsoup


【解决方案1】:

当您登录该站点时,它可能正在设置一个授权会话 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();

【讨论】:

  • @Jonathan Hedley,因为你创建了 JSoup,它非常有帮助。请帮我解决这个问题stackoverflow.com/questions/20908946/… 无论我做什么,都会在 iframe 末尾添加 &lt &gt 编码。谢谢 Swaraj
  • 但是如何获取 HttpOnly cookie?
【解决方案2】:
//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 检查此链接:stackoverflow.com/questions/19851747/login-facebook-via-jsoup
  • 嘿伙计,我按照你说的做了。但我没有得到“urlYouNeedToBeLoggedInToAccess”的网页。请回答我。
  • 不适合我。 org.jsoup.HttpStatusException: HTTP error fetching URL. Status=400,
【解决方案3】:

代码在哪里:

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

我遇到了困难,直到我将其更改为:

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

现在它可以完美运行了。

【讨论】:

    【解决方案4】:

    这是你可以尝试的……

    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();
    }
    

    询问是否需要进一步的帮助。

    【讨论】:

      【解决方案5】:
      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
      

      【讨论】:

      • 欢迎来到 SO。请在发布答案之前阅读how-to-answer。这段代码是什么意思?
      • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
      【解决方案6】:

      为什么要重新连接? 如果有任何 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();
                      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多