Jsoup详解,Jsoup.connect(“url”).get()

超、凢脫俗 2022-09-13 04:16 464阅读 0赞

Jsoup是一款Java的HTML解析器,主要用来对HTML解析。官网icon-default.png_t_L892https://jsoup.org/

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

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

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

所以,主要还是用来对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的元素。

◇从URL获取HTML来解析

  1. Document doc = Jsoup.connect("http://www.baidu.com/").get();
  2. String title = doc.title();

其中Jsoup.connect(“xxx”)方法返回一个org.jsoup.Connection对象。
在Connection对象中,我们可以执行get或者post来执行请求。但是在执行请求之前,
我们可以使用Connection对象来设置一些请求信息。比如:头信息,cookie,请求等待时间,代理等等来模拟浏览器的行为。

  1. Document doc = Jsoup.connect("http://example.com")
  2. .data("query", "Java")
  3. .userAgent("Mozilla")
  4. .cookie("auth", "token")
  5. .timeout(3000)
  6. .post();

◆获得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的选择器字符串,来查找指定元素。

例子:

  1. File input = new File("/tmp/input.html");
  2. Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
  3. Elements links = doc.select("a[href]"); //带有href属性的a元素
  4. Elements pngs = doc.select("img[src$=.png]");
  5. //扩展名为.png的图片
  6. Element masthead = doc.select("div.masthead").first();
  7. //class等于masthead的div标签
  8. Elements resultLinks = doc.select("h3.r > a"); //在h3元素之后的a元素

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

tagname: 通过标签查找元素,比如:a
  ns|tag: 通过标签在命名空间查找元素,比如:可以用 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)

获得一个属性的值,例如取得超链接中href的值

综合实例:采集开源中国项目信息

  1. package com.company;
  2. import org.jsoup.Jsoup;
  3. import org.jsoup.nodes.Document;
  4. import org.jsoup.nodes.Element;
  5. import org.jsoup.select.Elements;
  6. import java.io.IOException;
  7. import java.util.HashSet;
  8. import java.util.Set;
  9. public class Main {
  10. public static void main(String[] args) throws IOException {
  11. // write your code here
  12. Set<String> setUrls = new HashSet<>();
  13. for(int i = 1; i <= 5; i++)
  14. {
  15. String strUrl = "https://www.oschina.net/project/list?company=0&sort=score&lang=0&recommend=false&p="+i;
  16. setUrls.add(strUrl);
  17. }
  18. Set<String> setProjUrls = new HashSet<>();
  19. for(String stringUrl : setUrls)
  20. {
  21. Document document = Jsoup.connect(stringUrl)
  22. .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0")
  23. .get();
  24. // System.out.println(document);
  25. Elements elements = document.select("div.box.item");
  26. for(Element element : elements)
  27. {
  28. Elements eleUrl = element.select("div.box-aw a");
  29. String strPrjUrl = eleUrl.attr("href");
  30. setProjUrls.add(strPrjUrl);
  31. // System.out.println(strPrjUrl);
  32. Elements eleTitle = eleUrl.select(".title");
  33. String strTitle = eleTitle.text();
  34. // System.out.println(strTitle);
  35. Elements eleSummary = eleUrl.select(".summary");
  36. String strSummary = eleSummary.text();
  37. // System.out.println(strSummary);
  38. }
  39. }
  40. for(String stringUrl : setProjUrls)
  41. {
  42. Document document = Jsoup.connect(stringUrl)
  43. .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0")
  44. .get();
  45. Elements elements = document.select("div.box-aw a h1");
  46. String strTitle = elements.text();
  47. System.out.println("标题:" + strTitle);
  48. Elements elementsSection = document.select("section.list");
  49. int nSize = elementsSection.get(0).children().size();
  50. if(nSize == 0)
  51. continue;
  52. Element elementProtocol = elementsSection.get(0).child(0);
  53. Elements elesPro = elementProtocol.select("span");
  54. String strPro = elesPro.text();
  55. System.out.println("开源协议:" + strPro);
  56. nSize--;
  57. if(nSize == 0)
  58. continue;
  59. Element elementLan = elementsSection.get(0).child(1);
  60. Elements elesLan = elementLan.select("span").get(0).children();
  61. StringBuilder strlan = new StringBuilder();
  62. for(Element ele : elesLan)
  63. {
  64. String strLanTemp = ele.text();
  65. if(strLanTemp.indexOf("查看源码")>=0)
  66. break;
  67. strlan.append(strLanTemp+",");
  68. }
  69. if(elesLan.size()>0)
  70. {
  71. String strLanguage = strlan.toString().substring(0,strlan.length()-1);
  72. System.out.println("开发语言:" + strLanguage);
  73. }
  74. nSize--;
  75. if(nSize == 0)
  76. continue;
  77. Element elementOS = elementsSection.get(0).child(2);
  78. Elements elesOS = elementOS.select("span");
  79. String strOS = elesOS.text();
  80. System.out.println("操作系统:" + strOS);
  81. nSize--;
  82. if(nSize == 0)
  83. continue;
  84. Element elementAuthor = elementsSection.get(0).child(3);
  85. Elements elesAuthor = elementAuthor.select("a.link");
  86. String strAuthor= elesAuthor.text();
  87. System.out.println("软件作者;" + strAuthor);
  88. System.out.println("---------------------");
  89. }
  90. }
  91. }

爬取腾讯首页全部图片

  1. package com.company;
  2. import org.jsoup.Connection;
  3. import org.jsoup.Jsoup;
  4. import org.jsoup.nodes.Document;
  5. import org.jsoup.nodes.Element;
  6. import org.jsoup.select.Elements;
  7. import java.io.*;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.net.URLEncoder;
  12. public class meizi {
  13. /**
  14. * 下载图片到指定目录
  15. *
  16. * @param filePath 文件路径
  17. * @param imgUrl 图片URL
  18. */
  19. public static void downImages(String filePath, String imgUrl) {
  20. // 若指定文件夹没有,则先创建
  21. File dir = new File(filePath);
  22. if (!dir.exists()) {
  23. dir.mkdirs();
  24. }
  25. // 截取图片文件名
  26. String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());
  27. try {
  28. // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号
  29. String urlTail = URLEncoder.encode(fileName, "UTF-8");
  30. // 因此要将加号转化为UTF-8格式的%20
  31. imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");
  32. } catch (UnsupportedEncodingException e) {
  33. e.printStackTrace();
  34. }
  35. // 写出的路径
  36. File file = new File(filePath + File.separator + fileName);
  37. try {
  38. // 获取图片URL
  39. URL url = new URL(imgUrl);
  40. // 获得连接
  41. URLConnection connection = url.openConnection();
  42. // 设置10秒的相应时间
  43. connection.setConnectTimeout(10 * 1000);
  44. // 获得输入流
  45. InputStream in = connection.getInputStream();
  46. // 获得输出流
  47. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  48. // 构建缓冲区
  49. byte[] buf = new byte[1024];
  50. int size;
  51. // 写入到文件
  52. while (-1 != (size = in.read(buf))) {
  53. out.write(buf, 0, size);
  54. }
  55. out.close();
  56. in.close();
  57. } catch (MalformedURLException e) {
  58. e.printStackTrace();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. public static void main(String[] args) {
  64. // 利用Jsoup获得连接
  65. Connection connect = Jsoup.connect("http://www.qq.com");
  66. try {
  67. // 得到Document对象
  68. Document document = connect.get();
  69. // 查找所有img标签
  70. Elements imgs = document.getElementsByTag("img");
  71. System.out.println("共检测到下列图片URL:");
  72. System.out.println("开始下载");
  73. // 遍历img标签并获得src的属性
  74. for (Element element : imgs) {
  75. //获取每个img标签URL "abs:"表示绝对路径
  76. String imgSrc = element.attr("abs:src");
  77. // 打印URL
  78. System.out.println(imgSrc);
  79. //下载图片到本地
  80. meizi.downImages("d:/img", imgSrc);
  81. }
  82. System.out.println("下载完成");
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }

解析json(悟空问答网案例)

  1. package com.company;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import org.jsoup.Connection;
  6. import org.jsoup.Jsoup;
  7. import java.io.IOException;
  8. /**
  9. * Created by Administrator on 2018/8/8.
  10. */
  11. public class hello {
  12. public static void main(String[] args) throws IOException {
  13. Connection.Response res = Jsoup.connect("https://www.wukong.com/wenda/web/nativefeed/brow/?concern_id=6300775428692904450&t=1533714730319&_signature=DKZ7mhAQV9JbkTPBachKdgyme4")
  14. .header("Accept", "*/*")
  15. .header("Accept-Encoding", "gzip, deflate")
  16. .header("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
  17. .header("Content-Type", "application/json;charset=UTF-8")
  18. .header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
  19. .timeout(10000).ignoreContentType(true).execute();//.get();
  20. String body = res.body();
  21. System.out.println(body);
  22. JSONObject jsonObject2 = JSON.parseObject(body);
  23. JSONArray jsonArray = jsonObject2.getJSONArray("data");
  24. //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的
  25. //遍历方式1
  26. int size = jsonArray.size();
  27. for (int i = 0; i < size; i++){
  28. JSONObject jsonObject = jsonArray.getJSONObject(i);
  29. if(jsonObject.containsKey("question"))
  30. {
  31. JSONObject jsonObject3 = jsonObject.getJSONObject("question");
  32. String qid = jsonObject3.getString("qid");
  33. System.out.println(qid);
  34. }
  35. }
  36. }
  37. }

fastjson补充

json字符串-数组类型与JSONArray之间的转换

  1. /**
  2. * json字符串-数组类型与JSONArray之间的转换
  3. */
  4. public static void testJSONStrToJSONArray(){
  5. JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
  6. //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的
  7. //遍历方式1
  8. int size = jsonArray.size();
  9. for (int i = 0; i < size; i++){
  10. JSONObject jsonObject = jsonArray.getJSONObject(i);
  11. System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
  12. }
  13. //遍历方式2
  14. for (Object obj : jsonArray) {
  15. JSONObject jsonObject = (JSONObject) obj;
  16. System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
  17. }
  18. }

复杂json格式字符串与JSONObject之间的转换

  1. /**
  2. * 复杂json格式字符串与JSONObject之间的转换
  3. */
  4. public static void testComplexJSONStrToJSONObject(){
  5. JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
  6. //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON,所以这样也是可以的
  7. String teacherName = jsonObject.getString("teacherName");
  8. Integer teacherAge = jsonObject.getInteger("teacherAge");
  9. JSONObject course = jsonObject.getJSONObject("course");
  10. JSONArray students = jsonObject.getJSONArray("students");
  11. }

另一个实例(采集悟空问答某个问题的评论信息)

  1. package com.company;
  2. import org.jsoup.Connection;
  3. import org.jsoup.Jsoup;
  4. import org.jsoup.nodes.Document;
  5. import org.jsoup.nodes.Element;
  6. import org.jsoup.select.Elements;
  7. import java.io.*;
  8. public class meizi {
  9. public static void main(String[] args) {
  10. // 利用Jsoup获得连接
  11. Connection connect = Jsoup.connect("https://www.wukong.com/question/6586953004245582083/");
  12. try {
  13. // 得到Document对象
  14. Document document = connect.get();
  15. Elements elements = document.select(".question-name");
  16. System.out.println(elements.get(0).text());
  17. Elements elements2 = document.select(".answer-item");
  18. for(Element element : elements2)
  19. {
  20. Elements elements3 = element.select(".answer-user-avatar img");
  21. System.out.println(elements3.attr("abs:src"));
  22. elements3 = element.select(".answer-user-name");
  23. System.out.println(elements3.text());
  24. elements3 = element.select(".answer-user-tag");
  25. System.out.println(elements3.text());
  26. elements3 = element.select(".answer-text");
  27. System.out.println(elements3.text());
  28. }
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

发表评论

表情:
评论列表 (有 0 条评论,464人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jsoup

    jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQu

    相关 jsoup

    一、Jsoup概述 1.1、简介     jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,

    相关 Jsoup笔记

    1. 什么是Jsoup Jsoup是一款Java 的HTML(html也是XML文档)解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的AP

    相关 爬虫Jsoup

    爬虫Jsoup 简介 导入jar 简单示例 简介 Jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提