Java爬虫之JSoup使用教程

title: Java爬虫之JSoup使用教程
date: 2018-12-24 8:00:00 +0800
update: 2018-12-24 8:00:00 +0800
author: me
cover: https://img-blog.csdnimg.cn/20181224144920712
tags:

  • 第三方类库
    preview: JSoup是一个用于处理HTML的Java库,它提供了一个非常方便类似于使用DOM,CSS和jquery的方法的API来提取和操作数据。

文章目录

封面图

Java爬虫之JSoup使用教程

代码下载地址

https://github.com/suveng/demo/releases/tag/jsoupDemo

实战获取githubpages的链接,并生成sitemap

介绍

JSoup是一个用于处理HTML的Java库,它提供了一个非常方便类似于使用DOM,CSS和jquery的方法的API来提取和操作数据。

jsoup实现WHATWG HTML5规范,并将HTML解析为与现代浏览器相同的DOM。

  • 从URL,文件或字符串中提取并解析HTML。
  • 查找和提取数据,使用DOM遍历或CSS选择器。
  • 操纵HTML元素,属性和文本。
  • 根据安全的白名单清理用户提交的内容,以防止XSS攻击。
  • 输出整洁的HTML。

jsoup旨在处理发现所有格式有差异的HTML; 从原始和验证,到无效的标签; jsoup将创建一个明智的解析树。

项目地址

能用Jsoup实现什么?

  • 从URL,文件或字符串中刮取并解析HTML
  • 查找和提取数据,使用DOM遍历或CSS选择器
  • 操纵HTML元素,属性和文本
  • 根据安全的白名单清理用户提交的内容,以防止XSS攻击
  • 输出整洁的HTML

文档地址

主要类

1. org.jsoup.Jsoup类

Jsoup类是任何Jsoup程序的入口点,并将提供从各种来源加载和解析HTML文档的方法。

Jsoup类的一些重要方法如下:

方法

描述

static Connection connect(String url)

创建并返回URL的连接。

static Document parse(File in, String charsetName)

将指定的字符集文件解析成文档。

static Document parse(String html)

将给定的html代码解析成文档。

static String clean(String bodyHtml, Whitelist whitelist)

从输入HTML返回安全的HTML,通过解析输入HTML并通过允许的标签和属性的白名单进行过滤。

2. org.jsoup.nodes.Document类

该类表示通过Jsoup库加载HTML文档。可以使用此类执行适用于整个HTML文档的操作。

Element类的重要方法可以参见 - http://jsoup.org/apidocs/org/jsoup/nodes/Document.html

3. org.jsoup.nodes.Element类

HTML元素是由标签名称,属性和子节点组成。 使用Element类,您可以提取数据,遍历节点和操作HTML。

Element类的重要方法可参见 - http://jsoup.org/apidocs/org/jsoup/nodes/Element.html

简单使用

安装

使用maven导包,也可以使用jar

1<dependency> 2 <!-- jsoup HTML parser library @ http://jsoup.org/ --> 3 <groupId>org.jsoup</groupId> 4 <artifactId>jsoup</artifactId> 5 <version>1.10.2</version> 6</dependency>

加载文档

1. URL加载文档

从URL加载文档,使用Jsoup.connect()方法从URL加载HTML。

1try 2{ 3 4 5 6 Document document = Jsoup.connect("http://www.yiibai.com").get(); 7 System.out.println(document.title()); 8} 9catch (IOException e) 10{ 11 12 13 14 e.printStackTrace(); 15}

2. 从文件加载文档

使用Jsoup.parse()方法从文件加载HTML。

1try 2{ 3 4 5 6 Document document = Jsoup.parse( new File( "D:/temp/index.html" ) , "utf-8" ); 7 System.out.println(document.title()); 8} 9catch (IOException e) 10{ 11 12 13 14 e.printStackTrace(); 15}

3. 从String加载文档

使用Jsoup.parse()方法从字符串加载HTML。

1try 2{ 3 4 5 6 String html = "<html><head><title>First parse</title></head>" 7 + "<body><p>Parsed HTML into a doc.</p></body></html>"; 8 Document document = Jsoup.parse(html); 9 System.out.println(document.title()); 10} 11catch (IOException e) 12{ 13 14 15 16 e.printStackTrace(); 17}

提取数据

使用DOM方法导航文档

元素提供了一系列类似DOM的方法来查找元素,并提取和操作它们的数据。DOM getter是上下文的:在父文档上调用,他们在文档下找到匹配的元素; 他们在一个子元素上调用了那个孩子下面的元素。通过这种方式,您可以了解所需的数据。

寻找元素
  • getElementById(String id)
  • getElementsByTag(String tag)
  • getElementsByClass(String className)
  • getElementsByAttribute(String key) (及相关方法)
  • 元素的兄弟姐妹:siblingElements()firstElementSibling()lastElementSibling()nextElementSibling()previousElementSibling()
  • 图:parent()children()child(int index)
处理元素数据
  • attr(String key)获取和attr(String key, String value)设置属性
  • attributes() 获得所有属性
  • id()className()classNames()
  • text()获取和text(String value)设置文本内容
  • html()获取和html(String value)设置内部HTML内容
  • outerHtml() 获取外部HTML值
  • data()获取数据内容(例如scriptstyle标签)
  • tag()tagName()
操纵HTML和文本
  • append(String html)prepend(String html)
  • appendText(String text)prependText(String text)
  • appendElement(String tagName)prependElement(String tagName)
  • html(String value)

使用selector-syntax查找元素

使用CSS或类似jquery的选择器语法来查找或操作元素。

使用Element.select(String selector)Elements.select(String selector)方法

jsoup元素支持CSS(或jquery)之类的选择器语法来查找匹配元素,从而允许非常强大和健壮的查询。

select方法在一个可用DocumentElement或在Elements。它是上下文的,因此您可以通过从特定元素中进行选择或通过链接选择调用来进行过滤。

Select返回一个Elements列表(as Elements),它提供了一系列提取和操作结果的方法。更多选择器的语法

从元素中提取属性,文本和HTML

在解析文档并找到一些元素之后,您将需要获取这些元素中的数据。

  • Element.id()
  • Element.tagName()
  • Element.className()Element.hasClass(String className)

您有一个包含相对URL的HTML文档,您需要将其解析为绝对URL

在HTML元素中,URL通常是相对于文档的locat编写的IOn : <a href="https://my.oschina.net/download">...</a>. 当您使用该Node.attr(String key)方法获取href属性时,它将按照源HTML中的指定返回。

如果要获取绝对URL,则会有一个属性键前缀abs:,该前缀将导致根据文档的基URI解析属性值(原始位置)ION): attr("abs:href")

对于此用例,在解析文档时指定基URI很重要。

如果您不想使用abs:前缀,还有一个方法Node.absUrl(String key)可以执行相同的操作,但可以通过自然属性键进行访问。

示例程序:列出链接

1public class ListLinks { 2 3 4 5 public static void main(String[] args) throws IOException { 6 7 8 9 Validate.isTrue(args.length == 1, "usage: supply url to fetch"); 10 String url = args[0]; 11 print("Fetching %s...", url); 12 13 Document doc = Jsoup.connect(url).get(); 14 Elements links = doc.select("a[href]"); 15 Elements media = doc.select("[src]"); 16 Elements imports = doc.select("link[href]"); 17 18 print("\nMedia: (%d)", media.size()); 19 for (Element src : media) { 20 21 22 23 if (src.tagName().equals("img")) 24 print(" * %s: <%s> %sx%s (%s)", 25 src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), 26 trim(src.attr("alt"), 20)); 27 else 28 print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); 29 } 30 31 print("\nImports: (%d)", imports.size()); 32 for (Element link : imports) { 33 34 35 36 print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel")); 37 } 38 39 print("\nLinks: (%d)", links.size()); 40 for (Element link : links) { 41 42 43 44 print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); 45 } 46 } 47 48 private static void print(String msg, Object... args) { 49 50 51 52 System.out.println(String.format(msg, args)); 53 } 54 55 private static String trim(String s, int width) { 56 57 58 59 if (s.length() > width) 60 return s.substring(0, width-1) + "."; 61 else 62 return s; 63 } 64}

示例输出

1Media: (38) 2 * img: <http://ycombinator.com/images/y18.gif> 18x18 () 3 * img: <http://ycombinator.com/images/s.gif> 10x1 () 4 * img: <http://ycombinator.com/images/grayarrow.gif> x () 5 * img: <http://ycombinator.com/images/s.gif> 0x10 () 6 * script: <http://www.co2stats.com/propres.php?s=1138> 7 * img: <http://ycombinator.com/images/s.gif> 15x1 () 8 * img: <http://ycombinator.com/images/hnsearch.png> x () 9 * img: <http://ycombinator.com/images/s.gif> 25x1 () 10 * img: <http://mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.) 11 12Imports: (2) 13 * link <http://ycombinator.com/news.css> (stylesheet) 14 * link <http://ycombinator.com/favicon.ico> (shortcut icon) 15 16Links: (141) 17 * a: <http://ycombinator.com> () 18 * a: <http://news.ycombinator.com/news> (Hacker News) 19 * a: <http://news.ycombinator.com/newest> (new) 20 * a: <http://news.ycombinator.com/newcomments> (comments) 21 * a: <http://news.ycombinator.com/leaders> (leaders) 22 * a: <http://news.ycombinator.com/jobs> (jobs) 23 * a: <http://news.ycombinator.com/submit> (submit) 24 * a: <http://news.ycombinator.com/x?fnid=JKhQjfU7gW> (login) 25 * a: <http://news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73> () 26 * a: <http://www.readwriteweb.com/archives/facebook_gets_faster_debuts_homegrown_php_compiler.php?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+readwriteweb+%28ReadWriteWeb%29&utm_content=Twitter> (Facebook speeds up PHP) 27 * a: <http://news.ycombinator.com/user?id=mcxx> (mcxx) 28 * a: <http://news.ycombinator.com/item?id=1094578> (9 comments) 29 * a: <http://news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73> () 30 * a: <http://groups.google.com/group/django-developers/msg/a65fbbc8effcd914> ("Tough. Django produces XHTML.") 31 * a: <http://news.ycombinator.com/user?id=andybak> (andybak) 32 * a: <http://news.ycombinator.com/item?id=1094649> (3 comments) 33 * a: <http://news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73> () 34 * a: <http://news.ycombinator.com/x?fnid=p2sdPLE7Ce> (More) 35 * a: <http://news.ycombinator.com/lists> (Lists) 36 * a: <http://news.ycombinator.com/rss> (RSS) 37 * a: <http://ycombinator.com/bookmarklet.html> (Bookmarklet) 38 * a: <http://ycombinator.com/newsguidelines.html> (Guidelines) 39 * a: <http://ycombinator.com/newsfaq.html> (FAQ) 40 * a: <http://ycombinator.com/newsnews.html> (News News) 41 * a: <http://news.ycombinator.com/item?id=363> (Feature Requests) 42 * a: <http://ycombinator.com> (Y Combinator) 43 * a: <http://ycombinator.com/w2010.html> (Apply) 44 * a: <http://ycombinator.com/lib.html> (Library) 45 * a: <http://www.webmynd.com/html/hackernews.html> () 46 * a: <http://mixpanel.com/?from=yc> ()

实战爬取个人博客链接,并生成sitemap.xml

步骤

  • 1 确定爬取链接
  • 2 获取当前链接页面所有链接
  • 3 过滤非本域名链接
  • 4 保存当前链接,判断当前链接是否已经被保存过了(set集合),若已保存,跳过,若未保存,跳回1
  • 5 根据生成的链接,构造符合google的sitemap标准的xml文件

核心代码

入口类main.java

1public class Main { 2 3 4 5 public static void main(String[] args) throws IOException { 6 7 8 9 Links links = new Links(); 10 //获取链接,并保存到links.log 11 links.myblog(links); 12 SiteMapXML siteMapXML = new SiteMapXML(); 13 siteMapXML.createSiteMap("links.log"); 14 //生成后删除 15 FileUtils.deleteQuietly(new File("links.log")); 16 } 17}

link.java 实现爬取链接

1/** 2 * @author 苏文广 created at 2018/12/22 3 * @Description: jsoup 教程 实战 爬取连接 4 */ 5@Data 6public class Links { 7 8 9 10 11 /** 12 * 我的域名 13 */ 14 private static final String DOMAIN = "https://suveng.github.io"; 15 /** 16 * 目标域名 17 */ 18 private String targetDomain = "https://suveng.github.io"; 19 /** 20 * 保存了的链接 21 */ 22 private Set<String> saved = new HashSet<>(); 23 24 /** 25 * 最终链接 26 */ 27 String targetHref; 28 29 public void myblog(Links jsoupMain) throws IOException { 30 31 32 33 Document doc = Jsoup.connect(Links.DOMAIN+"/blog").get(); 34 Elements links = doc.select("a[href]"); 35 jsoupMain.saveLinksByElements(links); 36 37} 38 private void saveLinksByElements(Elements links) throws IOException { 39 40 41 42 if (links == null) { 43 44 45 46 return; 47 } 48 for (Element element : links) { 49 50 51 52 //处理连接类型 53 dealwithHref(element); 54 if (!saved.contains(targetHref)) { 55 56 57 58 System.out.println("\nlink : " + targetHref); 59 System.out.println("text : " + element.text()); 60 Elements targetLink = getLinks(targetHref); 61 if (targetLink == null) { 62 63 64 65 return; 66 } 67 saveLinks(); 68 saveLinksByElements(targetLink); 69 } 70 } 71 } 72 73 /** 74 * 处理连接 75 */ 76 private void dealwithHref(Element element) { 77 78 79 80 81 targetHref=element.attr("abs:href"); 82 //处理编码 83 try { 84 85 86 87 this.targetHref = URLDecoder.decode(targetHref, "utf-8"); 88 } catch (UnsupportedEncodingException e) { 89 90 91 92 System.err.println("不支持的编码,建议换成utf-8"); 93 this.targetHref = null; 94 return; 95 } 96 dealwithDomain(); 97 } 98 99 /** 100 * 判断是否是当前域名,只有当前域名才支持爬取,不支持跨域 101 */ 102 private void dealwithDomain() { 103 104 105 106 if (!this.targetHref.contains(this.targetDomain)){ 107 108 109 110 this.targetHref=null; 111 } 112 } 113 114 /** 115 * 获取链接 116 * @param url targetHref 117 * @return document.select("a[href]"); 118 */ 119 private Elements getLinks(String url) { 120 121 122 123 try { 124 125 126 127 Connection connect = Jsoup.connect(url); 128 Document document; 129 document = connect.get(); 130 return document.select("a[href]"); 131 } catch (Exception e) { 132 133 134 135 System.err.println("错误链接"); 136 return null; 137 } 138 } 139 140 /** 141 * 保存链接 142 * @throws IOException 读写文件 143 */ 144 private void saveLinks() throws IOException { 145 146 147 148 saved.add(this.targetHref); 149 File links = new File("links.log"); 150 FileUtils.writeStringToFile(links, this.targetHref + '\n', "utf-8", true); 151 } 152}

siteMapXML.java 实现构造sitemap

采用dom4j 类库,估计还会写一个关于dom4j的文章

1/** 2 * @author 苏文广 created at 2018/12/22 3 * @Description: sitemap 生成工具类 4 */ 5public class SiteMapXML { 6 7 8 9 10 11 public void createSiteMap(String linksPath) throws IOException { 12 13 14 15 Document document = DocumentHelper.createDocument(); 16 Element locs = document.addElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9"); 17 List<String> strings = FileUtils.readLines(new File(linksPath), Charset.forName("utf-8")); 18 for (String url : strings) { 19 20 21 22 Element loc = locs.addElement("url","http://www.sitemaps.org/schemas/sitemap/0.9"); 23 loc.addElement("loc").setText(url); 24 loc.addElement("lastmod") 25 .setText(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE)); 26 } 27 writeAndFlush(document); 28 } 29 30 public void writeAndFlush(Document document) { 31 32 33 34 try { 35 36 37 38 OutputFormat format = OutputFormat.createPrettyPrint(); 39 format.setEncoding(document.getXMLEncoding()); 40 Writer fileWriter = new FileWriter("sitemap.xml"); 41 XMLWriter xmlWriter = new XMLWriter(fileWriter, format); 42 xmlWriter.write(document); 43 xmlWriter.close(); 44 } catch (IOException e) { 45 46 47 48 System.err.println("导出xml失败,检查 writeandflush()"); 49 } 50 } 51 52 /** 53 * 对xml格式化并写入文件 54 */ 55 protected void writeFile4Pretty(File file, Document document) throws IOException { 56 57 58 59 60 OutputFormat format = OutputFormat.createPrettyPrint(); 61 format.setEncoding(document.getXMLEncoding()); 62 XMLWriter writer = new XMLWriter(new FileWriter(file), format); 63 writer.write(document); 64 writer.flush(); 65 writer.close(); 66 } 67 68 /*** 69 * 格式化xml为string 70 */ 71 protected String prettysString(Document document) throws IOException { 72 73 74 75 OutputFormat format = OutputFormat.createPrettyPrint(); 76 format.setEncoding(document.getXMLEncoding()); 77 StringWriter stringWriter = new StringWriter(); 78 XMLWriter writer = new XMLWriter(stringWriter, format); 79 writer.write(document); 80 writer.close(); 81 return stringWriter.toString(); 82 } 83 84 85}

https://github.com/suveng/demo/releases/tag/jsoupDemo

实战获取githubpages的链接,并生成sitemap

参考文章

https://www.yiibai.com/jsoup

本文同步分享在 博客“suveng”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

swap空间的增减方法

(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap

Java获得今日零时零分零秒的时间(Date型)

publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS