jsoup web scraping
jsoup简介
jsoup是一款HTML解析器,可用与解析URL地址、HTML文本内同等,操作类似于jQuery,可通过DOM查找数据,操作数据, 使用时需引入jsoup jar
jsoup可以从包含字符串、url及本地文件加载html文档,生成Document对象,通过Document对象即可操作文档中的数据
eg:
//通过url
Document doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy").get(); //通过html 字符串
String html = "<html><head></head> <body><p>#####</p></body></html>";
Document doc = Jsoup.parse(html); //通过文件加载,第三个参数指示baseURL
File input = new File("D:/test.html");
Document doc = Jsoup.parse(input,"UTF-8","http://www.cnblogs.com/wishyouhappy");
数据操作eg:
Document doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy").get();
System.out.println(doc.title());
常用函数
parse相关:
static Document parse(File in, String charsetName)
static Document parse(File in, String charsetName, String baseUri)
static Document parse(InputStream in, String charsetName, String baseUri)
static Document parse(String html)
static Document parse(String html, String baseUri)
static Document parse(URL url, int timeoutMillis)
static Document parseBodyFragment(String bodyHtml)
static Document parseBodyFragment(String bodyHtml, String baseUri)
url connect相关:
Connection connect(String url) //根据给定的url(必须是http或https)来创建连接 Connection cookie(String name, String value) //发送请求时放置cookie
Connection data(Map<String,String> data) //传递请求参数
Connection data(String... keyvals) //传递请求参数 Document get() //以get方式发送请求并对返回结果进行解析
Document post()//以post方式发送请求并对返回结果进行解析 Connection userAgent(String userAgent)
Connection header(String name, String value) //添加请求头
Connection referrer(String referrer) //设置请求来源
获取html元素:
getElementById(String id) //用id获得元素
getElementsByTag(String tag) //用标签获得元素
getElementsByClass(String className) //用class获得元素
getElementsByAttribute(String key) //用属性获得元素 siblingElements(),
firstElementSibling(),
lastElementSibling();
nextElementSibling(),
previousElementSibling()
获取和设置元素的值:
attr(String key) //获得元素的数据
attr(String key, String value) //设置元素数据
attributes() //获得所以属性
id(),
className()
classNames()
text() //获得文本值
text(String value) //设置文本值
html() //获取html
html(String value)//设置html
outerHtml()
data()
tag() //获得tag
tagName() //获得tagname
添加元素:
append(String html),
prepend(String html)
appendText(String text),
prependText(String text)
appendElement(String tagName),
prependElement(String tagName)
选择器:
| tagname | 使用标签名来定位,例如 a |
|---|---|
| ns|tag | 使用命名空间的标签定位,例如 fb:name 来查找 <fb:name> 元素 |
| #id | 使用元素 id 定位,例如 #logo |
| .class | 使用元素的 class 属性定位,例如 .head |
| [attribute] | 使用元素的属性进行定位,例如 [href] 表示检索具有 href 属性的所有元素 |
| [^attr] | 使用元素的属性名前缀进行定位,例如 [^data-] 用来查找 HTML5 的 dataset 属性 |
| [attr=value] | 使用属性值进行定位,例如 [width=500] 定位所有 width 属性值为 500 的元素 |
| [attr^=value], [attr$=value], [attr*=value] | 这三个语法分别代表,属性以 value 开头、结尾以及包含 |
| [attr~=regex] | 使用正则表达式进行属性值的过滤,例如 img[src~=(?i)\.(png|jpe?g)] |
| * | 定位所有元素 |
| el#id | 定位 id 值某个元素,例如 a#logo -> <a id=logo href= … > |
|---|---|
| el.class | 定位 class 为指定值的元素,例如 div.head -> <div class="head">xxxx</div> |
| el[attr] | 定位所有定义了某属性的元素,例如 a[href] |
| 以上三个任意组合 | 例如 a[href]#logo 、a[name].outerlink |
| ancestor child | 这五种都是元素之间组合关系的选择器语法,其中包括父子关系、合并关系和层次关系。 |
| parent > child | |
| siblingA + siblingB | |
| siblingA ~ siblingX |
| :lt(n) | 例如 td:lt(3) 表示 小于三列 |
|---|---|
| :gt(n) | div p:gt(2) 表示 div 中包含 2 个以上的 p |
| :eq(n) | form input:eq(1) 表示只包含一个 input 的表单 |
| :has(seletor) | div:has(p) 表示包含了 p 元素的 div |
| :not(selector) | div:not(.logo) 表示不包含 class="logo" 元素的所有 div 列表 |
| :contains(text) | 包含某文本的元素,不区分大小写,例如 p:contains(oschina) |
| :containsOwn(text) | 文本信息完全等于指定条件的过滤 |
| :matches(regex) | 使用正则表达式进行文本过滤:div:matches((?i)login) |
| :matchesOwn(regex) | 使用正则表达式找到自身的文本 |
例子:
package jsoup; /**
*
* 创建人:wish
* 创建时间:2014年6月13日 下午1:22:49
*/
import java.io.IOException; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; public class BlogCatch {
/**
* main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception { // getArticleTitle("http://www.cnblogs.com/wishyouhappy");
Document doc = Jsoup.connect("http://www.cnblogs.com/wishyouhappy")
.data("query", "Java") // 请求参数
.userAgent("I ’ m jsoup") // 设置 User-Agent
.cookie("auth", "token") // 设置 cookie
.timeout(3000) // 设置连接超时时间
.post();
System.out.println(doc.title());
} /**
* 获取指定HTML 文档指定的body
* 传入html string
* @throws IOException
*/
@SuppressWarnings("unused")
private static void getBlogBodyByString(String html) {
Document doc = Jsoup.parse(html);
System.out.println(doc.body());
} /**
*
* getBlogBodyByURL 通过url获取文档body
* @param url
* @return
*
*/
@SuppressWarnings("unused")
private static void getBlogBodyByURL(String url) throws IOException {
// 从 URL 直接加载 HTML 文档
Document doc2 = Jsoup.connect(url).get();
String title = doc2.body().toString();
System.out.println(title);
} /**
*
* article 获取博客上的文章标题和链接
* @param url
* @return
* @Exception 异常对象
*/
public static void getArticleTitle(String url) {
Document doc;
try {
doc = Jsoup.connect(url).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","postTitle");
for (Element element :ListDiv) {
Elements links = element.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text().trim();
System.out.println(linkHref);
System.out.println(linkText);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
*
* getBlog 获取指定博客文章的内容
* @param name
* @return
* @Exception 异常对象
*/
public static void getBlog(String url) {
Document doc;
try {
doc = Jsoup.connect(url).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","postBody");
for (Element element :ListDiv) {
System.out.println(element.html());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
jsoup web scraping的更多相关文章
- Web Scraping with Python读书笔记及思考
Web Scraping with Python读书笔记 标签(空格分隔): web scraping ,python 做数据抓取一定一定要明确:抓取\解析数据不是目的,目的是对数据的利用 一般的数据 ...
- [Node.js] Web Scraping with Pagination and Advanced Selectors
When web scraping, you'll often want to get more than just one page of data. Xray supports paginatio ...
- <Web Scraping with Python>:Chapter 1 & 2
<Web Scraping with Python> Chapter 1 & 2: Your First Web Scraper & Advanced HTML Parsi ...
- Web scraping with Python (part II) « Jean, aka Sig(gg)
Web scraping with Python (part II) « Jean, aka Sig(gg) Web scraping with Python (part II)
- 《Web Scraping With Python》Chapter 2的学习笔记
You Don't Always Need a Hammer When Michelangelo was asked how he could sculpt a work of art as mast ...
- Web Scraping with Python
Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...
- 阅读OReilly.Web.Scraping.with.Python.2015.6笔记---Crawl
阅读OReilly.Web.Scraping.with.Python.2015.6笔记---Crawl 1.函数调用它自身,这样就形成了一个循环,一环套一环: from urllib.request ...
- 阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href
阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href 1.查找以<a>开头的所有文本,然后判断href是否在<a> ...
- 阅读OReilly.Web.Scraping.with.Python.2015.6笔记---BeautifulSoup---findAll
阅读OReilly.Web.Scraping.with.Python.2015.6笔记---BeautifulSoup---findAll 1..BeautifulSoup库的使用 Beautiful ...
随机推荐
- 物联网MQTT协议分析和开源Mosquitto部署验证
在<物联网核心协议—消息推送技术演进>一文中已向读者介绍了多种消息推送技术的情况,包括HTTP单向通信.Ajax轮询.Websocket.MQTT.CoAP等,其中MQTT协议为IBM制定 ...
- 第十四章 红黑树——C++代码实现
红黑树的介绍 红黑树(Red-Black Tree,简称R-B Tree),它一种特殊的二叉查找树.红黑树是特殊的二叉查找树,意味着它满足二叉查找树的特征:任意一个节点所包含的键值,大于等于左孩子的键 ...
- Qt 学习之路 :线程简介
现代的程序中,使用线程的概率应该大于进程.特别是在多核时代,随着 CPU 主频的提升,受制于发热量的限制,CPU 散热问题已经进入瓶颈,另辟蹊径地提高程序运行效率就是使用线程,充分利用多核的优势.有关 ...
- 基于 Quartz 开发企业级任务调度应用--转
Quartz 基本概念及原理 Quartz Scheduler 开源框架 Quartz 是 OpenSymphony 开源组织在任务调度领域的一个开源项目,完全基于 Java 实现.该项目于 2009 ...
- 从零开始学习jquery (二)
前面我们了解到了如何获取使用jquery,下面我们主要看看jquery的一些语法.基本的语法 $(selector).action(). 美元符号定义 jQuery 选择符(selector)&quo ...
- .Net程序员关于微信公众平台测试账户配置 项目总结
今天项目第一次验收,夜晚吃过晚饭后,想把项目中用到的关于微信配置总结一下,虽然网上关于这方面的资料很多很多,还有官方API,但是总感觉缺点什么,就像期初做这个项目时,各方面找了很久的资料,说说配置吧! ...
- excel - 统计字符个数综合案例
本文通过一个综合的案例来介绍excel统计字符数的一些方法和思路,供大家参考和学习. 下图是一个excel数据源截图,我们逐一讲解不同条件的统计字符数. 第一,统计A2所有的字符数,不论是汉字和数字. ...
- 抓取锁的sql语句-第三次修改
CREATE OR REPLACE PROCEDURE SOLVE_LOCK AS V_SQL VARCHAR2(3000); --定义 v_sql 接受抓取锁的sql语句CUR_LOCK SYS_R ...
- AutoLayout学习之理解intrinsicContentSize,Content Hugging Priority,Content Compression Resistance Priority
TableViewCell的高度计算应该是所有开发者都会使用到的东西,之前都是用代码计算的方法来计算这个高度.最近有时间看了几个计算Cell高度的方法.基本上都用到了AutoLayout,这篇首先介绍 ...
- c#求slope线性回归斜率
public class mySlope { // public List<double> Values { get; set; } public double SlopeResult { ...