Like many modern technologies, the ability to extract information from a Web site has several frameworks to choose from. The most popular are jsoup, Htmlunit and Selenium webdriver. We discuss jsoup in this article. Jsoup is an open source project that provides a powerful data extraction API. It can be used to parse the HTML in a given URL, file, or string. It can also manipulate HTML elements and attributes.
<!--https://mvnrepository.com/artifact/org.jsoup/jsoup- <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version> 1.11. 3</version> </dependency>
Public Static void Main (string[] args) { = "; = Jsoup.parse (HTML); System.out.println (Doc.title ()); = Doc.getelementsbytag ("P"); for (Element paragraph:paragraphs) { System.out.println (Paragraph.text ()); }
The parse () method is called to parse the input HTML and turn it into a document object. The method that invokes the object can manipulate and extract the data.
In the example above, we first output the title of the page. We then get all the elements with the label "P". We then output the text of each paragraph in turn.
Running this code, we can get the following output:
12
Parsing URLs using Jsoup
Parsing URLs is a bit different than parsing strings, but the rationale is the same:
Public class jsoupexample { publicstaticvoidthrows IOException { = Jsoup.connect ("https://www.wikipedia.org"). get (); = Doc.getelementsbyclass ("Other-project"); for (Element title:titles) { System.out.println (Title.text ()); }}}
To fetch data from a URL, you need to call the Connect () method, providing the URL as a parameter. Then get the HTML from the connection using get (). The output of this example is:
Commons freely usable photos && open wiki applicationwikisource free librarywikispecies free species Directorymeta-wiki Community Coordination & Documentation
As you can see, this program captures all the elements of class other-project.
Public void throws IOException { = Jsoup.connect ("https://www.wikipedia.org"). get (); = Doc.select ("a[href]"); for (Element link:links) { System.out.println ("\nlink:" + link.attr ("href")); System.out.println ("text:" + Link.text ()); } }
The result of the run is a very long list:
Parsing files using Jsoup
Public void throws URISyntaxException, IOException { = Classloader.getsystemresource ("page.html"); New File (Path.touri ()); = Jsoup.parse (Inputfile, "UTF-8"); System.out.println (Document.title ()); // Parse document in any }
If you want to parse a file, you don't need to send a request to the Web site, so don't worry about running the program that adds too much burden to the server. Although there are many limitations to this approach, and the data is static and therefore not suitable for many tasks, it provides a more legitimate and harmless way to analyze data.
The resulting document can be parsed in any way previously mentioned.
Java to do web crawling