jsoup抓取页面与页面解析提取数据
来源:互联网 发布:武术软件 编辑:程序博客网 时间:2024/05/21 07:54
前两天的工作是解析亚马逊的页面,获取需要的数据,所以呢,我就选择了jsoup,选择的版本是1.9.2,这个大家可以去joup官网()maven仓库那下载就是了,我就不多说了。
首先,科普下什么是jsoup(我也是用了才知道的,嘿嘿):
接下来,就参照官方API和自己的代码讲解一下jsoup的用法。、
//Creates a new Connection to a URL. Use to fetch and parse a HTML page. //创建一个新的连接到指定URL。用于获取和解析这个HTML页面Document doc = Jsoup.connect("https://jsoup.org/").get();//获取Jsoup官网,并返回一个Document对象
2、也可以把一个HTML字符串转为document对象,不管你这个html是否完整,它都可以解析包装成一个document对象
//把一个字符串解析成document对象String html = "<html><head><title>First parse</title></head>" + "<body><p>Parsed HTML into a doc.</p></body></html>";Document document = Jsoup.parse(html);
3、解析body碎片
@Testpublic void test02(){//解析一个不完整的HTML页面String html = "<div><p>Lorem ipsum.</p>";//该方法会自动补全标签,并为其添加html和body标签,使其转化为一个Document对象Document doc = Jsoup.parseBodyFragment(html);//获取doc的body部分Element body = doc.body();}
//根据CSDN的URL地址加载一个Document对象Document doc = Jsoup.connect("http://www.csdn.net/").get();//获取title内容String title = doc.title();
<pre style="margin-top: 0px; margin-bottom: 10px; padding: 10px; font-family: Consolas, monospace; overflow: auto; border-radius: 5px; color: rgb(25, 41, 67); background-color: rgb(231, 235, 242);"><span style="font-size: 15px; line-height: 15px;"></span>
Document doc = Jsoup.connect("http://example.com")<span style="font-family: arial, 宋体, sans-serif;">//指定连接的参数获取document .data("query", "Java") .userAgent("Mozilla") .cookie("auth", "token") .timeout(3000) .post();
5、从文件加载一个文档对象
@Testpublic void test01() throws IOException{//Jsoup.parse(File in, String charsetName, String baseUri)File input = new File("C:\\Users\\Administrator\\Desktop\\hello.txt");//baseUri 参数用于解决文件中URLs是相对路径的问题。如果不需要可以传入一个空的字符串。Document doc = Jsoup.parse(input, "UTF-8", "http://blog.csdn.net/");System.out.println(doc);}
6、使用DOM方法遍历一个对象
@Testpublic void test02() throws IOException{File input = new File("C:\\Users\\Administrator\\Desktop\\hello.txt");Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");//获取ID为content的元素Element content = doc.getElementById("content");//获取在conten里的标签为a的元素Elements links = content.getElementsByTag("a");for (Element link : links) {//获取a标签中属性为href的值 String linkHref = link.attr("href"); //获取a标签中的文本 String linkText = link.text();}}
说明
Elements这个对象提供了一系列类似于DOM的方法来查找元素,抽取并处理其中的数据。具体如下:
查找元素getElementById(String id)
getElementsByTag(String tag)
getElementsByClass(String className)
getElementsByAttribute(String key)
(and related methods)- 兄弟元素:
siblingElements()
,firstElementSibling()
,lastElementSibling()
;nextElementSibling()
,previousElementSibling()
- Graph:
parent()
,children()
,child(int index)
元素数据
attr(String key)
获取属性attr(String key, String value)
设置属性attributes()
获取所有属性id()
,className()
andclassNames()
text()
获取文本内容text(String value)
设置文本内容html()
获取元素内HTMLhtml(String value)
设置元素内的HTML内容outerHtml()
获取元素外HTML内容data()
获取数据内容(例如:script和style标签)tag()
andtagName()
操作HTML和文本
append(String html)
,prepend(String html)
appendText(String text)
,prependText(String text)
appendElement(String tagName)
,prependElement(String tagName)
html(String value)
7、使用选择器语法来选择元素
@Testpublic void test03() throws IOException{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元素}
说明
jsoup elements对象支持类似于CSS (或jquery)的选择器语法,来实现非常强大和灵活的查找功能。.
这个select
方法在Document
, Element
,或Elements
对象中都可以使用。且是上下文相关的,因此可实现指定元素的过滤,或者链式选择访问。
Select方法将返回一个Elements
集合,并提供一组方法来抽取和处理结果。
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等
可以查看Selector
API参考来了解更详细的内容
@Testpublic void test04(){String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";Document doc = Jsoup.parse(html);//解析HTML字符串返回一个Document实现Element link = doc.select("a").first();//查找第一个a元素String text = doc.body().text(); // "An example link"//取得字符串中的文本String linkHref = link.attr("href"); // "http://example.com/"//取得链接地址String linkText = link.text(); // "example""//取得链接地址中的文本String linkOuterH = link.outerHtml(); // "<a href="http://example.com"><b>example</b></a>"String linkInnerH = link.html(); // "<b>example</b>"//取得链接内的html内容}
说明
上述方法是元素数据访问的核心办法。此外还其它一些方法可以使用:
Element.id()
Element.tagName()
Element.className()
andElement.hasClass(String className)
这些访问器方法都有相应的setter方法来更改数据.
@Testpublic void test05() throws IOException{Document doc = Jsoup.connect("http://www.open-open.com").get();Element link = doc.select("a").first();String relHref = link.attr("href"); // == "/"String absHref = link.attr("abs:href"); // "http://www.open-open.com/"}
说明
在HTML元素中,URLs经常写成相对于文档位置的相对路径: <a href="/download">...</a>
. 当你使用 Node.attr(String key)
方法来取得a元素的href属性时,它将直接返回在HTML源码中指定定的值。
假如你需要取得一个绝对路径,需要在属性名前加 abs:
前缀。这样就可以返回包含根路径的URL地址attr("abs:href")
因此,在解析HTML文档时,定义base URI非常重要。
如果你不想使用abs:
前缀,还有一个方法能够实现同样的功能 Node.absUrl(String key)
。
这个示例程序将展示如何从一个URL获得一个页面。然后提取页面中的所有链接、图片和其它辅助内容。并检查URLs和文本信息。
运行下面程序需要指定一个URLs作为参数
package org.jsoup.examples;import org.jsoup.Jsoup;import org.jsoup.helper.Validate;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import java.io.IOException;/** * Example program to list links from a URL. */public class ListLinks { public static void main(String[] args) throws IOException { Validate.isTrue(args.length == 1, "usage: supply url to fetch"); String url = args[0]; print("Fetching %s...", url); Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); Elements media = doc.select("[src]"); Elements imports = doc.select("link[href]"); print("\nMedia: (%d)", media.size()); for (Element src : media) { if (src.tagName().equals("img")) print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), trim(src.attr("alt"), 20)); else print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); } print("\nImports: (%d)", imports.size()); for (Element link : imports) { print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel")); } print("\nLinks: (%d)", links.size()); for (Element link : links) { print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); } } private static void print(String msg, Object... args) { System.out.println(String.format(msg, args)); } private static String trim(String s, int width) { if (s.length() > width) return s.substring(0, width-1) + "."; else return s; }
示例输入结果
Fetching http://news.ycombinator.com/...Media: (38) * img: <http://ycombinator.com/images/y18.gif> 18x18 () * img: <http://ycombinator.com/images/s.gif> 10x1 () * img: <http://ycombinator.com/images/grayarrow.gif> x () * img: <http://ycombinator.com/images/s.gif> 0x10 () * script: <http://www.co2stats.com/propres.php?s=1138> * img: <http://ycombinator.com/images/s.gif> 15x1 () * img: <http://ycombinator.com/images/hnsearch.png> x () * img: <http://ycombinator.com/images/s.gif> 25x1 () * img: <http://mixpanel.com/site_media/images/mixpanel_partner_logo_borderless.gif> x (Analytics by Mixpan.) Imports: (2) * link <http://ycombinator.com/news.css> (stylesheet) * link <http://ycombinator.com/favicon.ico> (shortcut icon) Links: (141) * a: <http://ycombinator.com> () * a: <http://news.ycombinator.com/news> (Hacker News) * a: <http://news.ycombinator.com/newest> (new) * a: <http://news.ycombinator.com/newcomments> (comments) * a: <http://news.ycombinator.com/leaders> (leaders) * a: <http://news.ycombinator.com/jobs> (jobs) * a: <http://news.ycombinator.com/submit> (submit) * a: <http://news.ycombinator.com/x?fnid=JKhQjfU7gW> (login) * a: <http://news.ycombinator.com/vote?for=1094578&dir=up&whence=%6e%65%77%73> () * 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) * a: <http://news.ycombinator.com/user?id=mcxx> (mcxx) * a: <http://news.ycombinator.com/item?id=1094578> (9 comments) * a: <http://news.ycombinator.com/vote?for=1094649&dir=up&whence=%6e%65%77%73> () * a: <http://groups.google.com/group/django-developers/msg/a65fbbc8effcd914> ("Tough. Django produces XHTML.") * a: <http://news.ycombinator.com/user?id=andybak> (andybak) * a: <http://news.ycombinator.com/item?id=1094649> (3 comments) * a: <http://news.ycombinator.com/vote?for=1093927&dir=up&whence=%6e%65%77%73> () * a: <http://news.ycombinator.com/x?fnid=p2sdPLE7Ce> (More) * a: <http://news.ycombinator.com/lists> (Lists) * a: <http://news.ycombinator.com/rss> (RSS) * a: <http://ycombinator.com/bookmarklet.html> (Bookmarklet) * a: <http://ycombinator.com/newsguidelines.html> (Guidelines) * a: <http://ycombinator.com/newsfaq.html> (FAQ) * a: <http://ycombinator.com/newsnews.html> (News News) * a: <http://news.ycombinator.com/item?id=363> (Feature Requests) * a: <http://ycombinator.com> (Y Combinator) * a: <http://ycombinator.com/w2010.html> (Apply) * a: <http://ycombinator.com/lib.html> (Library) * a: <http://www.webmynd.com/html/hackernews.html> () * a: <http://mixpanel.com/?from=yc> ()
11、设置属性值
在你解析一个Document之后可能想修改其中的某些属性值,然后再保存到磁盘或都输出到前台页面。
方法
可以使用属性设置方法 Element.attr(String key, String value)
, 和 Elements.attr(String key, String value)
.
假如你需要修改一个元素的 class
属性,可以使用 Element.addClass(String className)
和Element.removeClass(String className)
方法。
Elements
提供了批量操作元素属性和class的方法,比如:要为div中的每一个a元素都添加一个rel="nofollow"
可以使用如下方法:
doc.select("div.comments a").attr("rel", "nofollow");
说明
与Element
中的其它方法一样,attr
方法也是返回当 Element
(或在使用选择器是返回 Elements
集合)。这样能够很方便使用方法连用的书写方式。比如:
doc.select("div.masthead").attr("title", "jsoup").addClass("round-box");
12、设置元素的html内容Element div = doc.select("div").first(); // <div></div>div.html("<p>lorem ipsum</p>"); // <div><p>lorem ipsum</p></div>div.prepend("<p>First</p>");//在div前添加html内容div.append("<p>Last</p>");//在div之后添加html内容// 添完后的结果: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>Element span = doc.select("span").first(); // <span>One</span>span.wrap("<li><a href='http://example.com/'></a></li>");// 添完后的结果: <li><a href="http://example.com"><span>One</span></a></li>
说明
Element.html(String html)
这个方法将先清除元素中的HTML内容,然后用传入的HTML代替。Element.prepend(String first)
和Element.append(String last)
方法用于在分别在元素内部HTML的前面和后面添加HTML内容Element.wrap(String around)
对元素包裹一个外部HTML内容。
Element div = doc.select("div").first(); // <div></div>div.text("five > four"); // <div>five > four</div>div.prepend("First ");div.append(" Last");// now: <div>First five > four Last</div>
说明
文本设置方法与 HTML setter 方法一样:
Element.text(String text)
将清除一个元素中的内部HTML内容,然后提供的文本进行代替Element.prepend(String first)
和Element.append(String last)
将分别在元素的内部html前后添加文本节点。
对于传入的文本如果含有像 <
, >
等这样的字符,将以文本处理,而非HTML。
- 14、消除不受信任的html (来防止xss攻击)
在做网站的时候,经常会提供用户评论的功能。有些不怀好意的用户,会搞一些脚本到评论内容中,而这些脚本可能会破坏整个页面的行为,更严重的是获取一些机要信息,此时需要清理该HTML,以避免跨站脚本cross-site scripting攻击(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>
说明
XSS又叫CSS (Cross Site Script) ,跨站脚本攻击。它指的是恶意攻击者往Web页面里插入恶意html代码,当用户浏览该页之时,嵌入其中Web里面的html代码会被执行,从而达到恶意攻击用户的特殊目的。XSS属于被动式的攻击,因为其被动且不好利用,所以许多人常忽略其危害性。所以我们经常只让用户输入纯文本的内容,但这样用户体验就比较差了。
一个更好的解决方法就是使用一个富文本编辑器WYSIWYG如CKEditor 和 TinyMCE。这些可以输出HTML并能够让用户可视化编辑。虽然他们可以在客户端进行校验,但是这样还不够安全,需要在服务器端进行校验并清除有害的HTML代码,这样才能确保输入到你网站的HTML是安全的。否则,攻击者能够绕过客户端的Javascript验证,并注入不安全的HMTL直接进入您的网站。
jsoup的whitelist清理器能够在服务器端对用户输入的HTML进行过滤,只输出一些安全的标签和属性。
jsoup提供了一系列的Whitelist
基本配置,能够满足大多数要求;但如有必要,也可以进行修改,不过要小心。
这个cleaner非常好用不仅可以避免XSS攻击,还可以限制用户可以输入的标签范围。
- jsoup抓取页面与页面解析提取数据
- 使用JSOUP抓取页面数据
- Jsoup学习-使用Jsoup抓取页面数据
- 使用Jsoup 抓取页面的数据
- Android 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- android 使用Jsoup 抓取页面的数据
- 使用Jsoup 异步抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup抓取页面的数据
- 使用Jsoup 抓取页面的数据
- 使用Jsoup 抓取页面的数据
- Android项目的目录结构
- Eclipse修改tomcat的部署路径
- BZOJ3590【状压DP】
- 寄存器间接寻址方式
- Luogu P1569 KC与龙珠 解题报告
- jsoup抓取页面与页面解析提取数据
- 多线程
- UVALive 4960 Sensor network(MST+LCA)
- 目标检测相关文章及源码
- Linux学习笔记3 常用shell命令
- Linux内核模块简介
- Ubuntu 14.04 64位安装 Google 的 Tensorflow
- 菜鸟学习maven的安装配置
- const.char类型形参与LPWSTR类型的实参不兼容