Top-Bot
Top-Bot

Reputation: 892

Return element containing keyword in Jsoup

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

Answers (1)

Jonathan Hedley
Jonathan Hedley

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

Related Questions