zardlemalefique zardlemalefique - 1 year ago 112
Java Question

Java scrap webiste with login required using Jsoup

I'd like to printsome datas (div with class="news_article") from I created an account and I need to log in to access those datas.

Can anyone explain me why this code is not working ? I've tried a lot but nothing is working.

public static final String SPLIT_INTERNET_URL = "";
public static final String SPLIT_LOGIN = "";

* @param args the command line arguments
* @throws
* @throws
* @throws java.text.ParseException
* @throws java.lang.ClassNotFoundException
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException, ParseException, ClassNotFoundException {
// TODO code application logic here
Response res = Jsoup.connect(SPLIT_LOGIN)
.data("loginemail", "XXXXX", "password", "XXXX")
Document doc = res.parse();

Map<String, String> cookies = res.cookies();

Document pageWhenAlreadyLoggedIn = Jsoup.connect(SPLIT_INTERNET_URL).cookies(cookies).get();
Elements elems ="div[class=news_article]");
for (Element elem : elems) {

Answer Source

Your code doesn't log you in to the website....Try the below code to login to the website.

To login to the website:

Connection.Response res = Jsoup.connect(SPLIT_LOGIN)
            .data("action", "account", 
                "redirect", "account_home.php?",
                "radiobutton", "old", 
                "loginemail", "XXXXX",
                "password", "XXXXX", 
                "LoginChoice", "Sign In to Secure Area")
            .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36")

So you are now logged in, however the website seems to detect whether you are logged in in other browser or connection, requests that you terminate that connection first. So below is the code for terminating the connection:

Connection.Response res2 = Jsoup.connect("")
            .data("ok", "End Prior Session")
            .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36")

All good, now res2 will contains the home page of your account, you can then proceed to go to whatever page you want. For more information on how to login to a website with Jsoup, take a look at the following tutorial:

How to login to a website with Jsoup

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download