Open a connection with Jsoup, get status code and parse document

前端 未结 4 1106
春和景丽
春和景丽 2021-01-02 19:26

I\'m creating a class using jsoup that will do the following:

  1. The constructor opens a connection to a url.
  2. I have a method that will check the status
4条回答
  •  死守一世寂寞
    2021-01-02 20:01

    If you don't need to login, use:

    Document doc = Jsoup.connect("url").get();
    

    If you DO need to login I'd advise using:

    Response res = Jsoup.connect("url")
        .data("loginField", "yourUser", "passwordField", "yourPassword")
        .method(Method.POST)
        .execute();
    Document doc = res.parse();
    
    //If you need to keep logged in to the page, use
    Map cookies = res.cookies;
    
    //And by every consequent connection, you'll need to use
    Document pageWhenAlreadyLoggedIn = Jsoup.connect("url").cookies(cookies).get();
    

    In your usage to get urls I'd probably try

    Elements elems = doc.select(a[href]);
    for (Element elem : elems) {
        String link = elem.attr("href");
    }
    

    That's about it.. Keep up the good work

提交回复
热议问题