网站内容抓取(Excel教程Excel函数Excel表格制作Excel2010Excel实用技巧Excel视频教程)

优采云 发布时间: 2021-10-11 22:16

  网站内容抓取(Excel教程Excel函数Excel表格制作Excel2010Excel实用技巧Excel视频教程)

  我对网页内容的爬取比较感兴趣,所以就简单的学习了一下。如果我不使用任何框架来抓取网页内容,感觉有点困难。我会继续前进。这里使用的jsoup框架,爬取网页的内容和使用jquery选择网页的内容类似,上手很快。下面就来简单介绍一下吧!

  首先是获取网络资源的方法:

   /**

* 获取网络中的超链接

*

* @param urlStr

* 传入网络地址

* @return 返回网页中的所有的超链接信息

*/

public String getInternet(String urlStr, String encoding) {

URL url = null;

URLConnection conn = null;

String nextLine = null;

StringBuffer sb = new StringBuffer();

// 设置系统的代理信息

Properties props = System.getProperties();

props.put("proxySet", "true");

props.put("proxyHost", "10.27.16.212");

props.put("proxyPort", "3128");

System.setProperties(props);

try {

// 获取网络资源

url = new URL(urlStr);

// 获取资源连接

conn = url.openConnection();

conn.setReadTimeout(30000);//设置30秒后超时

conn.connect();

BufferedReader reader = new BufferedReader(new InputStreamReader(

conn.getInputStream(), encoding));

// 开始读取网页信息获取网页中的超链接信息

while ((nextLine = reader.readLine()) != null) {

sb.append(nextLine);

}

} catch (Exception e) {

e.printStackTrace();

}

return sb.toString();

}

  获取到网络资源后,我们可以根据自己的需要筛选出对自己有用的资源,下面开始抢资源:

  public static void main(String[] args) {

MavenTest test = new MavenTest();

try {

String html = test.getInternet( "http://www.weather.com.cn/html/weather/101020100.shtml#7d","UTF-8");

//将html文档转换为Document文档

Document doc = Jsoup.parse(html);

//获取class为.weatherYubaoBox的div的元素

Elements tableElements = doc.select("div.weatherYubaoBox");

// System.out.println(tableElements.html());

//获取所有的th元素

Elements thElements = tableElements.select("th");

//打印出日期的标题信息

for (int i = 0; i < thElements.size(); i++) {

System.out.print(" "+thElements.get(i).text() + "\t");

}

// 输出标题之后进行换行

System.out.println();

//获取表格的tbody

Elements tbodyElements = tableElements.select("tbody");

for (int j = 1; j < tbodyElements.size(); j++) {

//获取tr中的信息

Elements trElements = tbodyElements.get(j).select("tr");

for (int k = 0; k < trElements.size(); k++) {

//获取单元格中的信息

Elements tdElements = trElements.get(k).select("td");

//根据元素的多少判断出白天和夜晚的

if (tdElements.size() > 6) {

for (int m = 0; m < tdElements.size(); m++) {

System.out.print(tdElements.get(m).text() + "\t");

}

// 白天的数据打印完成后进行换行

System.out.println();

}else{

for(int n =0; n < tdElements.size(); n++){

System.out.print("\t"+tdElements.get(n).text());

}

//打印完成夜间的天气信息进行换行处理

System.out.println();

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

  操作结果如下:

  

  最后,附上框架的地址:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线