Search code examples
javahtmlparsingjsoup

How do you use Jsoup to search for a string on a website?


I am trying to use Jsoup to search a website to see if it contains a string. Is this even possible, and if so, how is it done?


Solution

  • Yes it is possible and actually quite easy if you are using Jsoup. To simply see if a specific Web-Page contains a specific string then you might do something like the following example:

    Let say we want to see if the following string exists within the Jsoup home web-page (https://jsoup.org/):

    If you have any questions on how to use jsoup
    

    Your code could look something like this:

    String stringToFind = "If you have any questions on how to use jsoup";
    try {
        Document doc = Jsoup.connect("https://jsoup.org/").get();
        if (doc.text().contains(stringToFind)) {
            System.out.println("Yes...String exists in web-page.");
        }
        else {
            System.out.println("No...String does not exist in web-page.");
        }
    }
    catch (IOException ex) {
        // Do whatever you like to handle the exception...
    }