分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

jsoup入门

发布时间:2023-09-06 01:31责任编辑:彭小芳关键词:js

jsoup是一款Java的HTML解析器,主要用来对HTML解析。官网   中文文档

在爬虫的时候,当我们用HttpClient之类的框架,获取到网页源码之后,需要从网页源码中取出我们想要的内容,

就可以使用jsoup这类HTML解析器了。可以非常轻松的实现。

虽然jsoup也支持从某个地址直接去爬取网页源码,但是只支持HTTP,HTTPS协议,支持不够丰富。

所以,主要还是用来对HTML进行解析。

◆其中,要被解析的HTML可以是一个HTML的字符串,可以是一个URL,可以是一个文件。

org.jsoup.Jsoup把输入的HTML转换成一个org.jsoup.nodes.Document对象,然后从Document对象中取出想要的元素。

org.jsoup.nodes.Document继承了org.jsoup.nodes.Element,Element又继承了org.jsoup.nodes.Node类。里面提供了丰富的方法来获取HTML的元素。

◇解析HTML字符串

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

◇从URL获取HTML来解析

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

其中Jsoup.connect("xxx")方法返回一个org.jsoup.Connection对象。

在Connection对象中,我们可以执行get或者post来执行请求。但是在执行请求之前,

我们可以使用Connection对象来设置一些请求信息。比如:头信息,cookie,请求等待时间,代理等等来模拟浏览器的行为。

Document doc = Jsoup.connect("http://example.com") ?.data("query", "Java") ?.userAgent("Mozilla") ?.cookie("auth", "token") ?.timeout(3000) ?.post();

◇从文件加载HTML来解析

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

◆获得Document对象后,接下来就是解析Document对象,并从中获取我们想要的元素了。

Document中提供了丰富的方法来获取指定元素。

◇使用DOM的方式来取得  

  getElementById(String id):通过id来获取
  getElementsByTag(String tagName):通过标签名字来获取
  getElementsByClass(String className):通过类名来获取
  getElementsByAttribute(String key):通过属性名字来获取
  getElementsByAttributeValue(String key, String value):通过指定的属性名字,属性值来获取
  getAllElements():获取所有元素

◇通过类似于css或jQuery的选择器来查找元素

   使用的是Element类的下记方法:

    public Elements select(String cssQuery)

  通过传入一个类似于CSS或jQuery的选择器字符串,来查找指定元素。

例子:

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元素

选择器的更多语法(可以在org.jsoup.select.Selector中查看到更多关于选择器的语法):

  tagname: 通过标签查找元素,比如:a
  ns|tag: 通过标签在命名空间查找元素,比如:可以用 fb|name 语法来查找 <fb:name> 元素
  #id: 通过ID查找元素,比如:#logo
  .class: 通过class名称查找元素,比如:.masthead
  [attribute]: 利用属性查找元素,比如:[href]
  [^attr]: 利用属性名前缀来查找元素,比如:可以用[^data-] 来查找带有HTML5 Dataset属性的元素
  [attr=value]: 利用属性值来查找元素,比如:[width=500]
  [attr^=value], [attr$=value], [attr*=value]: 利用匹配属性值开头、结尾或包含属性值来查找元素,比如:[href*=/path/]
  [attr~=regex]: 利用属性值匹配正则表达式来查找元素,比如: img[src~=(?i)\.(png|jpe?g)]
  *: 这个符号将匹配所有元素


Selector选择器组合使用
  el#id: 元素+ID,比如: div#logo
  el.class: 元素+class,比如: div.masthead
  el[attr]: 元素+class,比如: a[href]
  任意组合,比如:a[href].highlight
  ancestor child: 查找某个元素下子元素,比如:可以用.body p 查找在"body"元素下的所有 p元素
  parent > child: 查找某个父元素下的直接子元素,比如:可以用div.content > p 查找 p 元素,也可以用body > * 查找body标签下所有直接子元素
  siblingA + siblingB: 查找在A元素之前第一个同级元素B,比如:div.head + div
  siblingA ~ siblingX: 查找A元素之前的同级X元素,比如:h1 ~ p
  el, el, el:多个选择器组合,查找匹配任一选择器的唯一元素,例如:div.masthead, div.logo


伪选择器selectors
  :lt(n): 查找哪些元素的同级索引值(它的位置在DOM树中是相对于它的父节点)小于n,比如:td:lt(3) 表示小于三列的元素
  :gt(n):查找哪些元素的同级索引值大于n,比如: div p:gt(2)表示哪些div中有包含2个以上的p元素
  :eq(n): 查找哪些元素的同级索引值与n相等,比如:form input:eq(1)表示包含一个input标签的Form元素
  :has(seletor): 查找匹配选择器包含元素的元素,比如:div:has(p)表示哪些div包含了p元素
  :not(selector): 查找与选择器不匹配的元素,比如: div:not(.logo) 表示不包含 class="logo" 元素的所有 div 列表
  :contains(text): 查找包含给定文本的元素,搜索不区分大不写,比如: p:contains(jsoup)
  :containsOwn(text): 查找直接包含给定文本的元素
  :matches(regex): 查找哪些元素的文本匹配指定的正则表达式,比如:div:matches((?i)login)
  :matchesOwn(regex): 查找自身包含文本匹配指定正则表达式的元素
注意  :上述伪选择器索引是从0开始的,也就是说第一个元素索引值为0,第二个元素index为1等

◆通过上面的选择器,我们可以取得一个Elements对象,它继承了ArrayList对象,里面放的全是Element对象。

接下来我们要做的就是从Element对象中,取出我们真正需要的内容。

通常有下面几种方法:

◇Element.text()

  这个方法用来取得一个元素中的文本。

◇Element.html()或Node.outerHtml()

  这个方法用来取得一个元素中的html内容

◇Node.attr(String key)

  获得一个属性的值,例如取得超链接<a href="">中href的值

◆HTML清理

  利用org.jsoup.safety.Cleaner类的clean方法,可以HTML,避免XSS攻击。

例子:

String unsafe = ??"<p><a href=‘http://example.com/‘ onclick=‘stealCookies()‘>Link</a></p>";String safe = Jsoup.clean(unsafe, Whitelist.basic());// now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>

◆综合实例:

这个例子将结合HttpClient来爬取页面的HTML,再利用Jsoup对页面进行分析,提取极客头条的内容。

package com.csdn;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class HttpClientJsoupTest01 { ???//url传入 "http://www.csdn.net/" ????public void get(String url) { ???????????????CloseableHttpClient client=HttpClients.createDefault(); ???//定义一个默认的请求客户端 ???????????????HttpGet get=new HttpGet(url); ???????????????//定义一个get请求 ???????CloseableHttpResponse response=null; ???????//定义一个响应 ???????????????try { ???????????response=client.execute(get); ???????????System.out.println(response.getStatusLine().getStatusCode());//打印响应状态码,200表示成功 ???????????HttpEntity entity=response.getEntity(); ???????//获取响应实体 ???????????String html=EntityUtils.toString(entity); ???//将实体的内容转换为字符串 ???????????????????????/** ????????????* 接下来就利用jsoup来解析前面取得的html,并获取csdn首页的极客头条栏目下的标题 ????????????*/ ???????????Document document=Jsoup.parse(html); ???//利用Jsoup类的静态方法,将html转换成一个Document对象 ???????????Element element=document.select("div.wrap .left .hot_blog ul").first(); ???//利用select选择器,取得需要的li元素集合 ???????????Elements elements= element.select("a"); ???//取得a链接的集合 ???????????????????????for (Element element2 : elements) { ???????????????System.out.println("标题:"+element2.attr("title")+" ???????-->> ???地址:"+element2.attr("href")); ???????????} ???????????????????} catch (ClientProtocolException e) { ???????????// TODO Auto-generated catch block ???????????e.printStackTrace(); ???????} catch (IOException e) { ???????????// TODO Auto-generated catch block ???????????e.printStackTrace(); ???????}finally { ???????????try { ???????????????response.close(); ???????????????client.close(); ???????????} catch (IOException e) { ???????????????// TODO Auto-generated catch block ???????????????e.printStackTrace(); ???????????} ???????} ???}}

GitHub下载

jsoup入门

原文地址:http://www.cnblogs.com/jpfss/p/8085511.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved