一、什么是爬虫
爬虫是一段程序,抓取互联网上的数据,保存到本地。
抓取过程:
1、使用程序模拟浏览器
2、向服务器发送请求。
3、服务器响应html
4、把页面中的有用的数据解析出来。
解析页面中的链接地址。
把链接地址添加到url队列中。
5、爬虫从url队列中取url,返回的操作。
二、爬虫的抓取环节
1、抓取页面。
可以使用java api中提供的URLConnection类发送请求。
推荐使用工具包HttpClient。
是apache旗下的一个开源项目。
可以模拟浏览器。
2、对页面进行解析。
使用Jsoup工具包。
可以像使用jQuery一样解析html。
二、HttpClient
可以使用HttpClient模拟浏览器。
1、使用HttpClient发送get请求
步骤:
@Test
public void testGet() throws Exception {
//1)创建一个HttpClient对象,使用CloseableHttpClient,使用HttpClients工具类创建。
CloseableHttpClient httpClient = HttpClients.createDefault();
//2)创建一个HttpGet对象,get对象封装请求的url
//HttpGet get = new HttpGet("http://bbs.itheima.com/search.php?mod=forum&searchid=50&orderby=lastpost&ascdesc=desc&searchsubmit=yes&kw=java");
HttpGet get = new HttpGet("https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=%E6%89%8B%E6%9C%BA&pvid=2d8c452b8a904b16afc71167f307f975");
//3)使用HttpClient执行请求
CloseableHttpResponse response = httpClient.execute(get);
//4)接收服务端响应的内容。
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
// 响应的内容包含响应头
int statusCode = statusLine.getStatusCode();
System.out.println(statusCode);
// 包含响应的内容(html)
HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity);
System.out.println(html);
//5)关闭连接
response.close();
httpClient.close();
}
2、使用HttpClient发送Post请求
步骤:
@Test
public void testPost() throws Exception {
//1)创建一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2)创建HttpPost对象,封装一个url
HttpPost post = new HttpPost("http://bbs.itheima.com/search.php");
//3)如果有参数就应该把参数封装到表单中。
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("mod", "forum"));
form.add(new BasicNameValuePair("searchid", "50"));
form.add(new BasicNameValuePair("orderby", "lastpost"));
form.add(new BasicNameValuePair("ascdesc", "desc"));
form.add(new BasicNameValuePair("searchsubmit", "yes"));
form.add(new BasicNameValuePair("kw", "java"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form);
post.setEntity(entity);
//4)使用HttpClient执行请求。
CloseableHttpResponse response = httpClient.execute(post);
//5)接收服务端响应html
HttpEntity resultEntity = response.getEntity();
String html = EntityUtils.toString(resultEntity);
System.out.println(html);
//6)关闭连接
response.close();
httpClient.close();
}
爬京东的数据,需要加上请求头(最近新出的规则,具体可以百度):
@Test
public void testHtts() throws Exception {
//创建一个HttpClient对象
CloseableHttpClient httpClient = HttpsUtils.getHttpClient();
//创建一个HttGet对象,封装url
HttpGet get = new HttpGet("https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=%E6%89%8B%E6%9C%BA&pvid=2d8c452b8a904b16afc71167f307f975");</