<!--爬虫仅支持1.8版本的jdk--> <!-- 爬虫需要的依赖--> <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version> </dependency><!-- 爬虫需要的日志依赖--> <dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.25</version> </dependency>
爬虫配置文件位置及存放位置
#爬虫日志配置文件 不写就报错 log4j.rootLogger=DEBUG,A1 log4j.logger.cn.itcast = DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss, SSS} 【%t】 【%c】-【%p】 %m%n
实例代码
package day02; import org.apache.http.HttpEntity; import org.apache.http.ParseException; 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.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils;import java.io.IOException;public class pacohngde2 {public static void main(String[] args) throws IOException {//创建连接池管理器PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();//设置最大连接数cm.setMaxTotal(100);//设置每个主机的最大连接数 就是说每个网页地址最多分配10个线程cm.setDefaultMaxPerRoute(10);lianjie(cm);}private static void lianjie(PoolingHttpClientConnectionManager cm) throws IOException {//不是每次创建新的Httpclient,而是从连接池中获取Httpclient对象CloseableHttpClient build = HttpClients.custom().setConnectionManager(cm).build();//输入需要爬取的网址地址HttpGet httpGet = new HttpGet("https://www.gushicimingju.com/gushi/tangshisanbaishou/"); // 把地址交给CloseableHttpResponse 去爬取数据CloseableHttpResponse execute = build.execute(httpGet);//4.解析响应,获取数据//判断状态码是否是200 200为正常型号 其他为异常if (execute.getStatusLine().getStatusCode() == 200) {try {//获取爬取数据HttpEntity httpEntity = execute.getEntity();//将爬取数据解析为utf-8格式String content = EntityUtils.toString(httpEntity, "utf8");//打印System.out.println(content);} catch (IOException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} finally {if (execute != null) {execute.close();}}}} }