jsoup学习分享

jsoup可以遍历一个html文档,即使其便签不是完整的,不是闭合的,都不是问题parse(String html)可以将字符串转换成一个document对象
比如

String html = "<html><head><title>First parse</title></head>"+ 
"<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc =Jsoup.parse(html);

doc就是一个html文档
Jsoup.connect(String url)从一个连接网站获取document对象

Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();

从一个文件加载一个文档Jsoup.parse(File in, String charsetName, String baseUri)

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

baseUri 可为空写为null,如果是本地文件可以直接省略
你想使用类似于CSS或jQuery的语法来查找和操作元素可以使用Element.select(String selector) 和 Elements.select(String selector) 方法实现:(Elements方法选择器API详见http://www.open-open.com/jsoup/selector-syntax.htm)

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

Elements links = doc.select("a[href]"); //带有href属性的a元素
Elements pngs = doc.select("img[src$=.png]");
  //扩展名为.png的图片

Element masthead = doc.select("div.masthead").first();
  //class等于masthead的div标签

Elements resultLinks = doc.select("h3.r > a"); //在h3元素之后的a元素

猜你喜欢

转载自blog.csdn.net/weixin_42754420/article/details/86680513