Jsoup select elements from dropdown menu

May 08, 2017, at 09:50 AM

I have been trying to access a specific element from a dropdown menu on a Steam leaderboard page. Is there a good way to access a specific 'option value'? I have tried the following code and it isn't grabbing any value (debugger shows levelName as ""). Any help is appreciated, thanks :)

String url = "http://steamcommunity.com/stats/592300/leaderboards/1900835";
Document document = Jsoup.connect(url).get();
String levelName = document.select("div#leaderHeader > option:contains(1900822)").val();
Answer 1

There are few mistakes in your code:

  • :contains doesn't check attributes, but text generated by element. If you want to find <option value="1900822">someText</option> using value="1900822" then you can use [attr=value] selector like option[value=1900822] (without quotes)
  • you used parent > child but <option ...> is child of <select ...> element, not <div id="leaderHeader">. This div is its ancestor, but it is not parent, so remove that >
  • I am not sure what you are trying to do with val() method here, but I am guessing you want to use text().

So you probably want:

String levelName = document.select("div#leaderHeader option[value=1900822]").text();

Just notice that there are some non-breaking spaces &nbsp; in result. You may want to replace them with simple spaces and after that trim leading and trailing ones.

levelName = levelName.replace((char)160,' ').trim();
Why Spring Integration failover don&#39;t show exception

Why Spring Integration failover don't show exception

I have some problem with Spring Integration dispatcher's failover that should show me Exception if my Message Handler fails

String equation answer in int form

String equation answer in int form

I am in a low-level java class where I need to make an app using java and JavaScriptI have decided to create a game that creates a random equation using addition, subtraction, multiplication, and division

How to apply a MVC pattern to this?

How to apply a MVC pattern to this?

As I don't know what to do with my components to organize a pattern MVC, my viewjava do all

Java optimization. Casting or instanciating new object

Java optimization. Casting or instanciating new object

This question might be related with this other one How much processing and memory use does casting take in Java?