Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find elements by substring of ID using selector-syntax Jsoup?

I have used Jsoup to fetch a page from a URL. I can extract the link of certain id using the following line of code:

Elements links = doc.select("a[href]#title0"); 

How can I find the elements if I only know the part of its ID for example 'title'. I know that I could find all the a links with the href and then iterate through the 'links' and check whether it's id contains 'title' substring or not however I would like to avoid this approach. Is there a way to filter the links in the selector and check whether it's id contains 'title' substring?

like image 953
Marcin S. Avatar asked Jan 03 '13 20:01

Marcin S.


2 Answers

You can use something like:

Elements links = doc.select("a[id^=nav]");

this would return all the links with id starting with string "nav"

The following will return all the links with id containing string "logo"

Elements links = doc.select("a[id~=logo]");
like image 63
Alex Ackerman Avatar answered Nov 14 '22 23:11

Alex Ackerman


@alex-ackerman 's answer is half correct, but the other half is wrong.

[attr^=valPrefix] elements with an attribute named "attr", and value starting with "valPrefix" [attr$=valSuffix] elements with an attribute named "attr", and value ending with "valSuffix" [attr*=valContaining] elements with an attribute named "attr", and value containing "valContaining" [attr~=regex] elements with an attribute named "attr", and value matching the regular expression The above may be combined in any order

http://jsoup.org/apidocs/org/jsoup/select/Selector.html

like image 23
Malek Avatar answered Nov 14 '22 22:11

Malek