Java网络爬虫学习
原创 已于 2025-08-07 15:33:05 修改 · 粉丝可见 · 122 阅读 · 0 · 0 GEO检测 · 编辑 文章链接:https://blog.csdn.net/hacker_51/article/details/142664968
Java是一种广泛使用的编程语言,尤其在企业级应用和大型系统中应用广泛。 Java在处理大规模数据和并发性能方面表现出色,这对于需要高性能网络爬虫的情况可能更有优势。
一、准备环境 引入pom坐标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <dependencies > <dependency > <groupId > org.apache.httpcomponents.client5</groupId > <artifactId > httpclient5</artifactId > <version > 5.2.1</version > </dependency > <dependency > <groupId > org.slf4j</groupId > <artifactId > slf4j-log4j12</artifactId > <version > 1.6.6</version > </dependency > </dependencies >
1 在resources文件资源创建log4j.properties
1 2 3 4 5 6 7 8 # log4j.properties log4j.rootLogger=DEBUG, stdout log4j.logger.org.mybatis.example.BlogMapper=TRACE log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
测试发送 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.angindem.test;import org.apache.hc.client5.http.classic.methods.HttpGet;import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.core5.http.HttpEntity;import org.apache.hc.core5.http.ParseException;import org.apache.hc.core5.http.io.entity.EntityUtils;import java.io.IOException;public class CrawlerFirst { public static void main (String[] args) throws IOException, ParseException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet ("https://www.baidu.com/" ); CloseableHttpResponse response = httpClient.execute(httpGet); if (response.getCode() == 200 ){ HttpEntity httpEntity = response.getEntity(); String content = EntityUtils.toString(httpEntity, "UTF-8" ); System.out.println(content); }else { System.out.println("500" ); } response.close(); httpClient.close(); } }
运行代码
获取到了ok状态,发送并获取数据成功。
二、初识Java网络爬虫 1、Get请求带参数 通过 new URIBuilder 构造出 URI 对象,通过对象的setParam方法加入对应参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 package com.angindem.test;import org.apache.hc.client5.http.classic.methods.HttpGet;import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.core5.http.ParseException;import org.apache.hc.core5.http.io.entity.EntityUtils;import org.apache.hc.core5.net.URIBuilder;import java.io.IOException;import java.net.URISyntaxException;public class HttpGetParamsTest { public static void main (String[] args) throws IOException, ParseException, URISyntaxException { CloseableHttpClient httpClient = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder ("http://yun.itheima.com/search" ); uriBuilder.setParameter("key" , "java" ); HttpGet httpGet = new HttpGet (uriBuilder.build()); CloseableHttpResponse response = httpClient.execute(httpGet); int code = response.getCode(); if (code == 200 ){ System.out.println(code); String content = EntityUtils.toString(response.getEntity(),"UTF-8" ); System.out.println(content.length()); }else System.out.println(500 ); response.close(); httpClient.close(); } }
2、无参Post 请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package com.angindem.test;import org.apache.hc.client5.http.classic.methods.HttpPost;import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.core5.http.ParseException;import org.apache.hc.core5.http.io.entity.EntityUtils;import java.io.IOException;public class HttpPostTest { public static void main (String[] args) throws IOException, ParseException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost ("http://www.itcast.cn" ); CloseableHttpResponse response = httpClient.execute(httpPost); int code = response.getCode(); System.out.println("code = " + code); if (code == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content.length()); } else System.out.println(500 ); response.close(); httpClient.close(); } }
3、带参数Post请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.angindem.test;import org.apache.hc.client5.http.classic.methods.HttpPost;import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.core5.http.NameValuePair;import org.apache.hc.core5.http.ParseException;import org.apache.hc.core5.http.io.entity.EntityUtils;import org.apache.hc.core5.http.message.BasicNameValuePair;import java.io.IOException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;public class HttpPostParamsTest { public static void main (String[] args) throws IOException, ParseException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost ("http://yun.itheima.com/search" ); List <NameValuePair> params = new ArrayList <>(); params.add(new BasicNameValuePair ("key" ,"java" )); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (params, Charset.defaultCharset()); httpPost.setEntity(formEntity); CloseableHttpResponse response = httpClient.execute(httpPost); int code = response.getCode(); System.out.println("code = " + code); if (code == 200 ) { String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content.length()); } else System.out.println(500 ); response.close(); httpClient.close(); } }
4、配置HttpClient连接池 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package com.angindem.test;import org.apache.hc.client5.http.classic.methods.HttpGet;import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;import org.apache.hc.core5.http.ParseException;import org.apache.hc.core5.http.io.entity.EntityUtils;import java.io.IOException;public class HttpClientPoolTest { public static void main (String[] args) { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager (); cm.setMaxTotal(100 ); cm.setDefaultMaxPerRoute(10 ); try { doGet(cm); doGet(cm); } catch (IOException e) { throw new RuntimeException (e); } catch (ParseException e) { throw new RuntimeException (e); } } private static void doGet (PoolingHttpClientConnectionManager cm) throws IOException, ParseException { CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); HttpGet httpGet = new HttpGet ("http://www.itcast.cn" ); CloseableHttpResponse response = httpClient.execute(httpGet); String content = EntityUtils.toString(response.getEntity(), "UTF-8" ); System.out.println(content.length()); response.close(); } }
三、了解Java网路爬虫 jsoup 是一款Java 的HTML解析器,可直接解析某个 URL地址、HTML 文本内容。
它提供了一套非常省力的 API,可通过DOM,CSS 以及类似于jQuery 的操作方法来取出和操作数据。 jsoup的主要功能如下: 1、从一个URL,文件或字符串中解析 HTML; 2、使用DOM或CSS选择器来查找、取出数据; 3、可操作 HTML元素、属性、文本;
1、Jsoup工具 引入Jsoup的 pom坐标
1 2 3 4 5 6 <dependency > <groupId > org.jsoup</groupId > <artifactId > jsoup</artifactId > <version > 1.15.3</version > </dependency >
引入Junit 的 pom 坐标
1 2 3 4 5 <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.12</version > </dependency >
引入 commons-io 的 pom 坐标 用一些io工具类,比如 fileUtils
1 2 3 4 5 6 <dependency > <groupId > commons-io</groupId > <artifactId > commons-io</artifactId > <version > 2.11.0</version > </dependency >
引入 commons-lang3 的 pom 坐标 用一些String工具类,比如 StringUtils
1 2 3 4 5 6 <dependency > <groupId > org.apache.commons</groupId > <artifactId > commons-lang3</artifactId > <version > 3.12.0</version > </dependency >
测试Jsoup类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package jsoup;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.junit.Test;import java.io.IOException;import java.net.URL;public class JsoupTest { @Test public void testUrl () throws IOException { Document doc = Jsoup.parse(new URL ("http://www.itcast.cn" ), 1000 ); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); } }
PS:
虽然使用Jsoup可以替代Httpclient 直接发起请求解析数据,
但是往往不会这样用,因为实际的开发过程中,需要使用到多线程,连接池,代理等等方式,
而 jsoup 对这些的支持并不是很好,所以我们一般把jsoup 仅仅作为 Html解析工具使用。
2、解析字符串 test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <htmL > <head > <title > AngindemTestHtml</title > </head > <body > <div class ="city" > <h3 id ="city_bj" > 北京中心</h3 > <fb:img src ="/2018czgw/images/slogan.jpg" class ="slogan" /> <div class ="city_in" > <div class ="city_con" style ="display: none;" > <ul > <li id ="test" class ="class_a class_b" > <a href ="http://www.itcast.cn" target =" blank" > <span class ="s_name" > 北京</span > </a > </li > <li > <a href ="http://sh.itcast.cn" target =" blank" > <span class ="s_name" > 上海</span > </a > </li > <li > <a href ="http://gz.itcast.cn" target =" blank" > <span abc ="123" class ="s_name" > 广州</span > </a > </li > <ul > <li > 天津</li > </ul > </ul > </div > </div > </body > </html > </div >
通过Jsoup解析web结构字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testString () throws IOException { String content = FileUtils.readFileToString(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Document doc = Jsoup.parse(content); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); }
3、解析文件 通过Jsoup解析web文件
1 2 3 4 5 6 7 8 9 @Test public void testFile () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); }
4、使用Dom方式获取元素数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 package jsoup;import org.apache.commons.io.FileUtils;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.junit.Test;import java.io.File;import java.io.IOException;import java.net.URL;public class JsoupTest { @Test public void testUrl () throws IOException { Document doc = Jsoup.parse(new URL ("http://www.itcast.cn" ), 1000 ); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); } @Test public void testString () throws IOException { String content = FileUtils.readFileToString(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Document doc = Jsoup.parse(content); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); } @Test public void testFile () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); String title = doc.getElementsByTag("title" ).first().text(); System.out.println(title); } @Test public void testDom () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Element element = doc.getElementsByAttributeValue("href" ,"http://sh.itcast.cn" ).get(0 ); System.out.println("获取到的元素内容是 " + element.text()); } }
5、使用 attributes 属性 方式获取元素数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 @Test public void testData () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Element element = doc.getElementById("test" ); String result = "" ; result = element.text(); System.out.println("获取到的数据是:" + result); }
6、使用Select选择器方式获取元素数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Test public void testSelector () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Elements elements = doc.select("[class=s_name]" ); elements.forEach(element -> System.out.println(element.text())); }
7、使用 Select 任意组合方式获取元素数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Test public void testSelector2 () throws IOException { Document doc = Jsoup.parse(new File ("D:\\Java_workSpace\\StudyWebSpider\\src\\main\\resources\\test.html" ), "UTF-8" ); Element element = doc.select("h3#city_bj" ).first(); element = doc.select("span[abc].s_name" ).first(); System.out.println("获取到的内容是:" + element.text()); }