jsoup

作者: 陈大水牛 | 来源:发表于2018-05-09 12:03 被阅读0次

文章参考学习后总结
参考文章

https://www.yiibai.com/jsoup/jsoup-quick-start.html#article-start
https://blog.csdn.net/u010814849/article/details/52526582

获取对象方式:

方法 描述 case
static Connection connect(String url) 创建并返回URL的连接 case1
static Document parse(File in, String charsetName) 将指定的字符集文件解析成文档。 case2
static Document parse(String html) 将给定的html代码解析成文档。 case3
static String clean(String bodyHtml, Whitelist whitelist) 从输入HTML返回安全的HTML,通过解析输入HTML并通过允许的标签和属性的白名单进行过滤 case4

对应case1、case2、case3、case4:

    public static void main(String[] args) throws Exception {
        //case1:Jsoup.connect从网页获取title
        Document case1 = Jsoup.connect("http://www.baidu.com").get();
        System.out.println(case1.title());
        //打印内容“百度一下,你就知道”

        //case2:Jsoup.parse从文档获取title
        Document case2 = Jsoup.parse( new File( "D:/temp/index.html" ) , "utf-8" );
        System.out.println(case2.title());
        //打印内容“百度一下,你就知道”

        //case3:Jsoup.parse从网页获取title
        String html = "<html><head><title>百度一下,你就知道</title></head>"
                + "<body><p>Parsed HTML into a doc.</p></body></html>";
        Document case3 = Jsoup.parse(html);
        System.out.println(case3.title());
        //打印内容“百度一下,你就知道”


        //case4: Jsoup.clean
        String dirtyHTML = "<p><a href='http://www.yiibai.com/' onclick='sendCookiesToMe()'>Link</a></p>";
        String cleanHTML = Jsoup.clean(dirtyHTML, Whitelist.basic());
        System.out.println(cleanHTML);
        //  执行后输出结果如下<p><a href="http://www.yiibai.com/" rel="nofollow">Link</a></p>

        }

方法总结

(Document Elements  Element) 公用方法:
 Document document = Jsoup.connect("https://www.yiibai.com/").get();
        //getElementById(String idName)  根据id获取Element
        Element formElement = document.getElementById("footer-copyright");

        //document.text() 打印所有内容
        System.out.println(document.text());

        //getElementsByTag  根据标签属性获取(例如,input,Strong)
        Element formElement1=formElement.getElementsByTag("strong").first();
        System.out.println(formElement1.text());

//        根绝class获取Elements
        Element formElement = doc.getElementsByClass("fixed-btn").first();
        System.out.println(formElement);
        //<div class="fixed-btn"> </div>


        //attr(String name,String values)在获取标签后增加属性
        formElement1.attr("hi","我要替换");
        //替换后为 
        System.out.println(formElement1);
        //打印信息: <strong hi="我要替换"><a href="https://www.yiibai.com/" target="_blank">易百教程</a></strong>

        //Jsoup.clean
        String dirtyHTML = "<p><a href='http://www.yiibai.com/' onclick='sendCookiesToMe()'>Link</a></p>";
        String cleanHTML = Jsoup.clean(dirtyHTML, Whitelist.basic());
        System.out.println(cleanHTML);
        //  执行后输出结果如下<p><a href="http://www.yiibai.com/" rel="nofollow">Link</a></p>

        //根据标签里面的熟悉values获取 Element
        // Elementz 值为<meta name="keywords" content="VBScript, MATLAB, EJB, IPv6, IPv4, 电子商务, PostgreSQL, SQLite, SDLC, Assembly, 操作系统">
        String keywords = doc.select("meta[name=keywords]").first().attr("content");
        String keywords1 = doc.select("meta[name=keywords]").attr("content");
        System.out.println("Meta keyword : " + keywords);
        //打印内容为       Meta keyword : VBScript, MATLAB, EJB, IPv6, IPv4, 电子商务, PostgreSQL, SQLite, SDLC, Assembly, 操作系统, 

        //获取图片Element 并打印相关信息
        Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
        for (Element image : images) {
            System.out.println("src : " + image.attr("src"));
            System.out.println("height : " + image.attr("height")+"width : " + image.attr("width")+"alt : " + image.attr("alt"));
        }

        //获取input并打印key和values
        Elements inputElements = doc.getElementsByTag("input");
        for (Element inputElement : inputElements) {
            String key = inputElement.attr("name");
            String value = inputElement.attr("value");
            System.out.println("Param name: "+key+" \nParam value: "+value);
        }

        //获取网页title
        String title = doc.title();
        System.out.println("title is: " + title);
        //打印内容“title is: 易百教程™ - 专注于IT教程和实例”


       //要获取网页中的所有链接,请使用以下代码。
       Document document = Jsoup.connect("https://www.baidu.com/").get();
       Elements links = document.select("a[href]");
       //获取其中一个Element为:<a href="http://news.baidu.com" target="_blank" class="mnav">新闻</a>
            for (Element link : links)
            {
                //获取Element里面的 hrep和text
                System.out.println("link : " + link.attr("href"));
                //使用 abs:获得决定路径
                //String absHref = link.attr("abs:href"); 
                System.out.println("text : " + link.text());
            }

        Elements links = doc.select("a[href]"); //带有href属性的a元素
        Elements pngs = doc.select("img[src$=.png]"); //扩展名为.png的图片
        Element masthead = doc.select("div.fixed-btn").first();//class等于fixed-btn的div标签
       Element masthead = doc.select("div#footer-copyright").first();//id等于footer-copyright的div标签
      //参考Selector选择器 基本用法  组合器
        Elements resultLinks = doc.select("h3.r > a"); //在h3元素之后的a元素

        System.out.println(masthead);

      文本修改:
        Element  doch =Jsoup.parse("<div></div>").select("div").first();
        System.out.println(doch);
        //打印=<div></div>
        //增加text
        doch.text("TEST");
        System.out.println(doch);
        //打印<div>TEST</div>
        //text前面增加
        doch.prepend("前面添加");
        System.out.println(doch);
        //打印<div>    前面添加TEST    </div>
        //text后面增加
        doch.append("后面添加");
        //打印<div>     前面添加TEST后面添加    </div>
        System.out.println(doch);
//根据html  获取所有表单中的form的action  和input的name
 public static  Map getJdPayH5(String  respone){
     Map reqMap2 = new HashMap();
     Document doc = Jsoup.parse(respone);
    System.out.println(doc);
     reqMap2.put("requestUrl",doc.getElementsByTag("form").attr("action").toString());
     Elements times_links = doc.getElementsByTag("input");
     for(Element a :times_links){
           reqMap2.put(a.attr("name"),a.attr("value"));
        }
     return   reqMap2;
    }

Connection

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

查找元素:

getElementById(String id) id
getElementsByTag(String tag) 标签名
getElementsByClass(String className) class名
getElementsByAttribute(String key) 属性
siblingElements() 所有的兄弟元素
firstElementSibling() 第一个兄弟元素
lastElementSibling() 最后一个兄弟元素
nextElementSibling() 下一个兄弟元素
previousElementSibling() 上一个兄弟元素
parent() 获取该元素父节点
children() 获取该元素的子元素
child(int index) 获取该元素的第几个子元素(下标从0开始)

元素数据

attr(String key) 获取属性
attr(String key, String value) 设置属性
attributes() 获取所有属性
id() 获取该元素id
className() 获取该元素class,多个class之间空格隔开
classNames() 获取所有元素的class
text() 获取文本内容
text(String value) 设置文本内容
html() 获取元素内HTML
html(String value) 设置元素内的HTML内容
outerHtml() 获取元素外HTML内容
data() 获取数据内容(例如:script和style标签)
tag()
tagName() 获取元素标签名

操作HTML和文本

append(String html) 添加给定的html到元素末尾
prepend(String html) 添加给定html到元素前面
appendText(String text) 创建并添加文本
prependText(String text) 创建并添加文本
appendElement(String tagName) 添加到元素末尾
prependElement(String tagName) 添加到元素前
html(String value) 设置元素值

Selector选择器 基本用法

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] 利用匹配属性值开头、结尾或包含属性值来查找元素,比如:[href*=/path/]
[attr~=regex] 利用属性值匹配正则表达式来查找元素,例如img[src~=(?i).(png |jpe?g)]
* 定位所有元素

Selector选择器 组合使用

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 查找某个元素下子元素,比如:可以用.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) 使用正则表达式找到自身的文本

相关文章

网友评论

      本文标题:jsoup

      本文链接:https://www.haomeiwen.com/subject/oxlmrftx.html