需求:爬取百度百科内容,并进行解析。
(1)步骤:
-
抓取页面数据(使用HttpClient得到html)
-
解析页面数据(使用Jsoup解析html的文本内容)
PS:jsoup的功能(了解) 1)从一个URL,文件或字符串中解析HTML 2)使用DOM或CSS选择器来查找、取出数据 3)可操作HTML元素、属性、文本
(2)具体操作:
1.新建maven项目
2.修改pom文件,引入依赖
<!--引入httpclient:支持 HTTP 协议的客户端编程工具包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<!--引入jsoup:HTML解析器,可直接解析某个URL地址、HTML文本内容-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
3.java类
//参数query:表示用户输入的字符串(中文)
public static void main(String query) {
//将中文字符编码
String encodeStr = URLEncoder.encode(query,"utf-8");
System.out.println("处理后:" + encodeStr);
//1.生成httpclient,相当于该打开一个浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
//2.创建get请求,相当于在浏览器地址栏输入 网址
HttpGet request = new HttpGet("https://baike.baidu.com/item/"+encodeStr);
try {
//3.执行get请求,相当于在输入地址栏后敲回车键
response = httpClient.execute(request);
//4.判断响应状态为200,进行处理
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//5.获取响应内容
HttpEntity httpEntity = response.getEntity();
String html = EntityUtils.toString(httpEntity, "utf-8");
System.out.println(html);
//6.Jsoup解析html
Document document = Jsoup.parse(html);
//像js一样,通过标签获取title
System.out.println(document.getElementsByTag("h1").first());
//得到h1标签及内容
System.out.println(document.getElementsByClass("main-content"));
//得到类名为main-content的大标签及其内容
} else {
//如果返回状态不是200,比如404(页面不存在)等,根据情况做处理,这里略
System.out.println("返回状态不是200");
System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
}
}
运用到项目代码中,经过处理后效果如下:
原百度百科页面: