java中怎么利用Jsoup爬取网页,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
一,导入依赖
<!--java爬虫--> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.3</version> </dependency> <!--httpclient依赖--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
二,编写demo类
注意不要导错包了,是org.jsoup.nodes下面的
package com.taotao.entity; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class intefaceTest { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault();//创建httpClient HttpGet httpGet = new HttpGet("http://www.cnblogs.com/");//创建httpget实例 CloseableHttpResponse response = httpClient.execute(httpGet);//执行get请求 HttpEntity entity = response.getEntity();//获取返回实体 String content = EntityUtils.toString(entity,"utf-8");//网页内容 response.close();//关闭流和释放系统资源 Jsoup.parse(content); Document doc = Jsoup.parse(content);//解析网页得到文档对象 Elements elements = doc.getElementsByTag("title");//获取tag是title的所有dom文档 Element element = elements.get(0);//获取第一个元素 String title = element.text(); //.html是返回html System.out.println("网页标题:"+title); Element element1 = doc.getElementById("site_nav_top");//获取id=site_nav_top标签 String str = element1.text(); System.out.println("str:"+str); } }
看完上述内容,你们掌握java中怎么利用Jsoup爬取网页的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。