原文地址:http://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/

Jsoup, a HTML parser, its “jquery-like” and “regex” selector syntax is very easy to use and flexible enough to get whatever you want. Below are three examples to show you how to use Jsoup to get links, images, page title and “div” element content from a HTML page.

Download jsoup
The jsoup is available in Maven central repository. For non-Maven user, just download it from jsoup website.

pom.xml
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>

1. Grabs All Hyperlinks

This example shows you how to use jsoup to get page’s title and grabs all links from “google.com”.

HTMLParserExample1.java
package com.mkyong;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import java.io.IOException; public class HTMLParserExample1 { public static void main(String[] args) { Document doc;
try { // need http protocol
doc = Jsoup.connect("http://google.com").get(); // get page title
String title = doc.title();
System.out.println("title : " + title); // get all links
Elements links = doc.select("a[href]");
for (Element link : links) { // get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text()); } } catch (IOException e) {
e.printStackTrace();
} } }

Output

title : Google

link : http://www.google.com.my/imghp?hl=en&tab=wi
text : Images link : http://maps.google.com.my/maps?hl=en&tab=wl
text : Maps //omitted for readability
Note
It’s recommended to specify a “userAgent” in Jsoup, to avoid HTTP 403 error messages.

Document doc = Jsoup.connect("http://anyurl.com")
.userAgent("Mozilla")
.get();

2. Grabs All Images

The second example shows you how to use the Jsoup regex selector to grab all image files (png, jpg, gif) from “yahoo.com”.

HTMLParserExample2.java
package com.mkyong;

package com.mkyong;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import java.io.IOException; public class HTMLParserExample2 { public static void main(String[] args) { Document doc;
try { //get all images
doc = Jsoup.connect("http://yahoo.com").get();
Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
for (Element image : images) { System.out.println("\nsrc : " + image.attr("src"));
System.out.println("height : " + image.attr("height"));
System.out.println("width : " + image.attr("width"));
System.out.println("alt : " + image.attr("alt")); } } catch (IOException e) {
e.printStackTrace();
} } }

Output

src : http://l.yimg.com/a/i/mntl/ww/events/p.gif
height : 50
width : 202
alt : Yahoo! src : http://l.yimg.com/a/i/ww/met/intl_flag_icons/20111011/my_flag.gif
height :
width :
alt : //omitted for readability
 

3. Get Meta elements

The last example simulates an offline HTML page and use jsoup to parse the content. It grabs the “meta” keyword and description, and also the div element with the id of “color”.

HTMLParserExample3.java
package com.mkyong;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; public class HTMLParserExample3 { public static void main(String[] args) { StringBuffer html = new StringBuffer(); html.append("<!DOCTYPE html>");
html.append("<html lang=\"en\">");
html.append("<head>");
html.append("<meta charset=\"UTF-8\" />");
html.append("<title>Hollywood Life</title>");
html.append("<meta name=\"description\" content=\"The latest entertainment news\" />");
html.append("<meta name=\"keywords\" content=\"hollywood gossip, hollywood news\" />");
html.append("</head>");
html.append("<body>");
html.append("<div id='color'>This is red</div> />");
html.append("</body>");
html.append("</html>"); Document doc = Jsoup.parse(html.toString()); //get meta description content
String description = doc.select("meta[name=description]").get(0).attr("content");
System.out.println("Meta description : " + description); //get meta keyword content
String keywords = doc.select("meta[name=keywords]").first().attr("content");
System.out.println("Meta keyword : " + keywords); String color1 = doc.getElementById("color").text();
String color2 = doc.select("div#color").get(0).text(); System.out.println(color1);
System.out.println(color2); } }

Output

Meta description : The latest entertainment news
Meta keyword : hollywood gossip, hollywood news
This is red
This is red

4. Grabs Form Inputs

This code snippets shows you how to use Jsoup to grab HTML form inputs (name and value). For detail usage, please refer to this automate login a website with Java.

public void getFormParams(String html){

	Document doc = Jsoup.parse(html);

	//HTML form id
Element loginform = doc.getElementById("your_form_id"); Elements inputElements = loginform.getElementsByTag("input"); List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
} }

5. Get Fav Icon

This code shows you how to use Jsoup to page’s favourite icon.

jSoupExample.java
package com.mkyong;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; public class jSoupExample { public static void main(String[] args) { StringBuffer html = new StringBuffer(); html.append("<html lang=\"en\">");
html.append("<head>");
html.append("<link rel=\"icon\" href=\"http://example.com/image.ico\" />");
//html.append("<meta content=\"/images/google_favicon_128.png\" itemprop=\"image\">");
html.append("</head>");
html.append("<body>");
html.append("something");
html.append("</body>");
html.append("</html>"); Document doc = Jsoup.parse(html.toString()); String fav = ""; Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
if(element==null){ element = doc.head().select("meta[itemprop=image]").first();
if(element!=null){
fav = element.attr("content");
}
}else{
fav = element.attr("href");
}
System.out.println(fav);
} }

Output

http://example.com/image.ico

jsoup HTML parser hello world examples--转的更多相关文章

  1. Jsoup代码解读之四-parser

    Jsoup代码解读之四-parser 作为Java世界最好的HTML 解析库,Jsoup的parser实现非常具有代表性.这部分也是Jsoup最复杂的部分,需要一些数据结构.状态机乃至编译器的知识.好 ...

  2. Jsoup 解析 HTML

    Jsoup 文档 方法 要取得一个属性的值,可以使用Node.attr(String key) 方法 对于一个元素中的文本,可以使用Element.text()方法 对于要取得元素或属性中的HTML内 ...

  3. Jsoup代码解读之六-防御XSS攻击

    Jsoup代码解读之八-防御XSS攻击 防御XSS攻击的一般原理 cleaner是Jsoup的重要功能之一,我们常用它来进行富文本输入中的XSS防御. 我们知道,XSS攻击的一般方式是,通过在页面输入 ...

  4. HtmlUnit+Jsoup 解决爬虫无法解析执行javascript的问题

    本人最近在研究爬虫.作为一个新手.研究了些爬虫框架,发现所有开源的爬虫框架很多,功能也很齐全,但唯独遗憾的是,目前还没有发现那个爬虫对js完美的解释并执行.看了浅谈网络爬虫爬js动态加载网页(二)之后 ...

  5. Jsoup的学习

    一 . 什么是jsoup jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址.HTML文本内容.它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来 ...

  6. 【转】jsoup的使用

     Jsoup的使用   jsoup 是一款 Java 的HTML 解析器,可直接解析某个URL地址.HTML文本内容.它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法 ...

  7. Java | 技术应用 | 利用Jsoup处理页面

    根据微信公众号的推文链接地址,对文章内容进行爬取,利用jsoup解析文章源代码,加上结合xpth提取文文章信息, 利用正则表达式读取文章发表时间. Jsoup <!-- jsoup HTML p ...

  8. Java爬虫利器HTML解析工具-Jsoup

    Jsoup简介 Java爬虫解析HTML文档的工具有:htmlparser, Jsoup.本文将会详细介绍Jsoup的使用方法,10分钟搞定Java爬虫HTML解析. Jsoup可以直接解析某个URL ...

  9. JSOUP 爬虫

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.mavne 依赖: <!--html 解析 : jsoup HTML parser library @ ...

随机推荐

  1. 自定义安装MS Office Project2007会出错

    作者:朱金灿 来源:http://blog.csdn.net/clever101 今天使用虚拟光驱文件自定义安装MSOffice Project2007,如下图: 然后总是出现一个错误: 从网上找来一 ...

  2. 4) 十分钟学会android--建立第一个APP,启动另一个Activity

    在完成上一课(建立简单的用户界面)后,我们已经拥有了显示一个activity(一个界面)的app(应用),该activity包含了一个文本字段和一个按钮.在这节课中,我们将添加一些新的代码到MyAct ...

  3. 【转载】程序猿转型AI必须知道的几件事!

    历史上AI火过两次,但是最终都已销声匿迹作为结束.这次AI大火的原因:AlphaGo 4比1战胜李世石,相对于一些外行人的恐慌和恐惧,其实很多业内人员在这场世纪之战结束后,都为人类点上了一个大大的赞. ...

  4. Java 方法的应用

    Java方法可以理解为C#中的函数,都是把复杂的问题简单化,按模块,按功能区分,分别完成各个部分在调用这些方法完成整个功能. 方法的综合练习,猜数字的实现: 代码要求: 生成不重复的4位数字(只有1- ...

  5. 验证码识别 Tesseract的简单使用和总结

    Tesseract是什么 OCR即光学字符识别,是指通过电子设备扫描纸上的打印的字符,然后翻译成计算机文字的过程.也就是说通过输入图片,经过识别引擎,去识别图片上的文字.Tesseract是一种适用于 ...

  6. spring注解略解

    @Scope("prototype") 如果ACTION中不@Scope("prototype"),有可能报找不到XXXACTION的错误!写上这个就表示每次请 ...

  7. day22 包,相对/绝对路径

    目录 包 包被导入时发生的三件事 为什么要有包 相对路径 绝对路径 包 包是一个文件夹,也是一个模块,只是为了区分单个文件的模块,称之为包.因为单纯的文件夹无法作为模块,文件夹内的__init__.p ...

  8. 洛谷P2827 蚯蚓 队列 + 观察

    我们不难发现先被切开的两半一定比后被切开的两半大,这样就天然的生成了队列的单调性,就可以省去一个log.所以,我们开三个队列,分别为origin,big,smallorigin, big, small ...

  9. ubuntu重置root密码(转载自https://zhinan.sogou.com/guide/detail/?id=316512881651)

    ubuntu忘记root密码怎么办?如果普通用户忘记了怎么办 ### 第一种方法:无论你是否申请了root帐号,或是普通账号密码忘记了都没有问题的! 1. 重启ubuntu,随即长按shift进入gr ...

  10. C语言基础 (6) 类型转换,数组与随机数

    复习 1.隐式转换 Double a Int b = 1 A = b //编译器自动转换把b转换为double类型后 再给a赋值(隐式转换) 2.强制类型转换 (变量)类型名 Int a = 1 // ...