Reputation: 892
I am trying to get the element that contains my keyword in Jsoup. I have read about how to specify with elements, class and id.
I am wondering how to use a keyword to search a website and return the element containing the keyword.
Upvotes: 4
Views: 1640
Reputation: 10522
The selector to use to find an element with a given string (keyword) is :containsOwn(text)
.
Example
String html = "<p>Para one</p><p>Para <b>two keyword</b></p>";
Document doc = Jsoup.parse(html);
Element el = doc.select(":containsOwn(keyword)").first();
Element p = doc.select("p:contains(keyword)").first();
System.out.println(el.html());
System.out.println(p.html());
Output
two keyword
Para <b>two keyword</b>
For more details see the selector cookbook documentation.
The difference between contains
and containsOwn
is that the former will include results from child elements.
Upvotes: 4