Java爬虫(httpclient&jsoup)

时间:2020-07-11 12:39:42   收藏:0   阅读:53

简介

网络爬虫是一种按照一定的规则自动的抓取网页上面的信息的一种程序或脚本。
使用httpclient和jsoup可以爬虫网页信息。

httpclient

  1. 从一个url,文本或字符串中解析html
  2. 使用dom或css选择器来查找,取出数据
  3. 可操作html元素,属性,文本

解析url(jsoup可以直接输入url,发起请求并获取数据,封装为document对象)

      public void testJsoupUrl() throws Exception {
      //    解析url地址
      Document document = Jsoup.parse(new URL("http://www.jd.com/"), 1000);

      //获取title的内容
      Element title = document.getElementsByTag("title").first();
      System.out.println(title.text());
  }

使用dom方式遍历文档

  tagname: 通过标签查找元素,比如:span
  //tagname: 通过标签查找元素,比如:span
  Elements span = document.select("span");
  for (Element element : span) {
      System.out.println(element.text());
  }
  #id: 通过ID查找元素,比如:# city_bj)
  //#id: 通过ID查找元素,比如:#city_bjj
  String str = document.select("#city_bj").text();
  .class: 通过class名称查找元素,比如:.class_a
  //.class: 通过class名称查找元素,比如:.class_a
  str = document.select(".class_a").text();
  [attribute]: 利用属性查找元素,比如:[abc]
  //[attribute]: 利用属性查找元素,比如:[abc]
  str = document.select("[abc]").text();
  [attr=value]: 利用属性值来查找元素,比如:[class=s_name]
  //[attr=value]: 利用属性值来查找元素,比如:[class=s_name]
  str = document.select("[class=s_name]").text();
  el#id: 元素+ID,比如: h3#city_bj
  //el#id: 元素+ID,比如: h3#city_bj
  String str = document.select("h3#city_bj").text();
  el.class: 元素+class,比如: li.class_a
  //el.class: 元素+class,比如: li.class_a
  str = document.select("li.class_a").text();
  el[attr]: 元素+属性名,比如: span[abc]
  //el[attr]: 元素+属性名,比如: span[abc]
  str = document.select("span[abc]").text();
  任意组合: 比如:span[abc].s_name
  //任意组合,比如:span[abc].s_name
  str = document.select("span[abc].s_name").text();
  ancestor child: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有li
  //ancestor child: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有li
  str = document.select(".city_con li").text();
  parent > child: 查找某个父元素下的直接子元素,比如:

  //parent > child: 查找某个父元素下的直接子元素,
  //比如:.city_con > ul > li 查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级li
  str = document.select(".city_con > ul > li").text();
  .city_con > ul > li 查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级li
  parent > *: 查找某个父元素下所有直接子元素
  //parent > * 查找某个父元素下所有直接子元素.city_con > *
  str = document.select(".city_con > *").text();
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!