2020年寒假假期总结0115

  WebMagic的学习基础:Jsoup的学习(Jsoup基础API+Http+Jsoup实战爬取)

  Jsoup的Selector选择器API:

    @Test
    public void TestSelector() throws Exception {
        //解析文件
        Document document = Jsoup.parse(new File("C:\\Users\\SuperMan\\Desktop\\test.html"), "utf8");
        //通过标签查找元素
        Elements elements = document.select("span");
        for (Element e : elements
        ) {
            System.out.println(e.text());
        }
        //通过ID来查找元素 在id前加上#
        Element element = document.select("#city_bj").first();
        System.out.println(element.text());
        //通过属性来分析 中括号包围
        Element element1 = document.select("[abc]").first();
        System.out.println(element1.text());

        //通过Class查找 在查找内容前加上.   类似htnl文本
        Element element2 = document.select(".fdnav").first();
        System.out.println(element2.text());
        //通过属性-值的方式查找 中括号包围,等号表示匹配
        Elements elements1 = document.select("[class=icon_fuli]");
        for (Element e : elements1
        ) {
            System.out.println(e.text());
        }

    }

    Jsoup的Selector选择器组合的API:

    @Test
    public void testSelectorGroup() throws Exception {
        //解析文件
        Document document = Jsoup.parse(new File("C:\\Users\\SuperMan\\Desktop\\test.html"), "utf8");
        //el#id 元素加id
        Element element=document.select("h3#city_bj").first();
        System.out.println(element.text());
        //el.class 元素加class
        Element element1=document.select("span.s_name").first();
        System.out.println(element1.text());
        //el[sttr] 元素+属性名
        Element element2=document.select("span[abc]").first();
        System.out.println(element2.text());
        //任意组合
        Element element3=document.select("span[abc].s_name").first();
        System.out.println(element3.text());
        //ancestor child 查找某个元素下子元素
        Elements elements=document.select(".city_con li");
        for (Element e:elements
             ) {
            System.out.println(e.text());
        }
        //查找元素下的直接子元素
        Elements elements1=document.select(".city_con > ul >li");
        for (Element e:elements
             ) {
            System.out.println(e.text());
        }
        //查找父元素的所有直接子元素
        Elements elements2=document.select(".city_con >ul > *");
        for (Element e:elements2
             ) {
            System.out.println(e.text());
        }
    }

猜你喜欢

转载自www.cnblogs.com/heiyang/p/12199113.html