<dependency> <groupId>org.ops4j.pax.carrot</groupId> <artifactId>pax-carrot-html-parser</artifactId> <version>1.3.0</version> </dependency> import org.ops4j.pax.carrot.api.Interpreter; import org.ops4j.pax.carrot.api.ParserResult; import org.ops4j.pax.carrot.html.parser.HtmlDomInterpreter; import org.ops4j.pax.carrot.html.parser.HtmlParser; import java.io.IOException; import java.io.StringReader; public class WebPageScraper { public static void main(String[] args) { String html = "<html><head><title>Example</title></head><body><h1>My Web Page</h1><p>Welcome to my website!</p></body></html>"; HtmlParser htmlParser = new HtmlParser(); Interpreter interpreter = new HtmlDomInterpreter(); try (ParserResult result = htmlParser.parse(htmlParser.createContext(), new StringReader(html), interpreter)) { String title = result.getPath("head > title").getText(); String paragraph = result.getPath("body > p").getText(); System.out.println("Title: " + title); System.out.println("Paragraph: " + paragraph); } catch (IOException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文