Take text from a website span and return to the console

Asked

Viewed 72 times

-1

How can I take a website span and return the text on the console? I tried this way, but I don’t know how to get Span:

public void SpanSite(){
   URL url = new URL("https://google.com");
   BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
}

I accept other methods

1 answer

0


You can use the library jsoup for this. Example: to catch all the spans of google, you could do it this way:

Document doc = Jsoup.connect("https://www.google.com").get();
doc.select("span")
    .stream()
    .forEach(s -> System.out.println(s.text()));

Edit:

To search for an element that contains a certain text, you can use the Pseudo selectors :containsOwn(textoASerBuscado) or :matchesOwn(regex). Example:

Document doc = Jsoup.connect("https://www.google.com").get();
doc.select("span:containsOwn(google)")   //Busca todos os spans que contenham "google"
    .stream()
    .forEach(s -> System.out.println(s.text()));

To learn about other selectors, you can look at documentation of the Selector class

  • Ok, how can I check if it contains such span with such text on the site? For example: if(s. contains("Example")

  • @Betadarknight I edited and added an example in response to this case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.