imoteb imoteb - 6 months ago 12
HTML Question

Java Jsoup button selection

I just want to check whether given element exists or not, I have the following code:

Document doc = Jsoup.connect("http://www.gsmarena.com/news.php3?iPage=2").get();
Elements button = doc.select("a > pages-next");
if (!button.isEmpty()) {
System.out.println("contains");
} else {
System.out.println("not contains");
}


But it always returns false, here is also the element that I want to check:
enter image description here

TDG TDG
Answer

There are two issues here:

  1. The right selector is .pages-next and not a > pages-next.
  2. You must provide the user-agent string, or else you'll get a page with different DOM structure then the one you get with your browser.

Use this code -

Document doc = Jsoup.connect("http://www.gsmarena.com/news.php3?iPage=2")
             .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0")
             .get();
        Elements button = doc.select(".pages-next");
        if (!button.isEmpty()) {
            System.out.println("contains");
        } else {
              System.out.println("not contains");
        }