网络爬虫就是用程序帮助我们访问网络上的资源,我们一直以来都是使用HTTP协议访问互联网的网页,网络爬虫需要编写程序,在这里使用同样的HTTP协议访问网页。
这里我们使用Java的HTTP协议客户端 HttpClient这个技术,来实现抓取网页数据。
所需依赖
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.3version>
dependency>
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet请求
HttpGet httpGet = new HttpGet("");//爬取网页地址
//使用HttpClient发起请求
response = httpClient.execute(httpGet);
//获取请求数据
String content = EntityUtils.toString(response.getEntity(), “UTF-8”);
HttpPost httpPost = new HttpPost(“http://www.liujin.top”);
创建HttpPost对象,设置url访问地址
HttpPost httpPost = new HttpPost(“http://www.liujin.top/search”);
声明List集合,封装表单中的参数
List params = new ArrayList();
设置请求地址是:http://www.liujin.top/search?keys=Java
params.add(new BasicNameValuePair(“keys”,“Java”));
创建表单的Entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,“utf8”);
设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);
如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题
public static void main(String[] args) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// 设置最大连接数
cm.setMaxTotal(200);
// 设置每个主机的并发数
cm.setDefaultMaxPerRoute(20);
doGet(cm);
doGet(cm);
}
private static void doGet(PoolingHttpClientConnectionManager cm) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet = new HttpGet("http://www.liujin.top");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
// 判断状态码是否是200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放连接
if (response == null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
//不能关闭HttpClient
//httpClient.close();
}
}
}
public static void main(String[] args) throws IOException {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet请求
HttpGet httpGet = new HttpGet("http://www.liujin.top");
//设置请求参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1000)//设置创建连接的最长时间
.setConnectionRequestTimeout(500)//设置获取连接的最长时间
.setSocketTimeout(10 * 1000)//设置数据传输的最长时间
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//使用HttpClient发起请求
response = httpClient.execute(httpGet);
//判断响应状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
//如果为200表示请求成功,获取返回数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//打印数据长度
System.out.println(content);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放连接
if (response == null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
httpClient.close();
}
}
}
jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据
所需依赖
<dependency>
<groupId>org.jsoupgroupId>
<artifactId>jsoupartifactId>
<version>1.10.3version>
dependency>
Jsoup可以直接输入url,它会发起请求并获取数据,封装为Document对象
@Test
public void testJsoupUrl() throws Exception {
// 解析url地址,后面的1000ms指解析时间
Document document = Jsoup.parse(new URL("http://www.liujin.top"), 1000);
//获取title的内容
Element title = document.getElementsByTag("title").first();
System.out.println(title.text());
}
Jsoup可以直接输入字符串,并封装为Document对象
@Test
public void testJsoupString() throws Exception {
//读取文件获取
String html = FileUtils.readFileToString(new File("D:\\jsoup.html"), "UTF-8");
// 解析字符串
Document document = Jsoup.parse(html);
//获取title的内容
Element title = document.getElementsByTag("title").first();
System.out.println(title.text());
}
Jsoup可以直接解析文件,并封装为Document对象
@Test
public void testJsoupHtml() throws Exception {
// 解析文件
Document document = Jsoup.parse(new File("D:\\jsoup.html"),"UTF-8");
//获取title的内容
Element title = document.getElementsByTag("title").first();
System.out.println(title.text());
}
元素获取
id
查询元素getElementById
标签
获取元素getElementsByTag
class
获取元素getElementsByClass
属性
获取元素getElementsByAttribute
//1. 根据id查询元素getElementById
Element element = document.getElementById("city_bj");
//2. 根据标签获取元素getElementsByTag
element = document.getElementsByTag("title").first();
//3. 根据class获取元素getElementsByClass
element = document.getElementsByClass("s_name").last();
//4. 根据属性获取元素getElementsByAttribute
element = document.getElementsByAttribute("abc").first();
element = document.getElementsByAttributeValue("class", "city_con").first();
元素中获取数据
//获取元素
Element element = document.getElementById("test");
//1. 从元素中获取id
String str = element.id();
//2. 从元素中获取className
str = element.className();
//3. 从元素中获取属性的值attr
str = element.attr("id");
//4. 从元素中获取所有属性attributes
str = element.attributes().toString();
//5. 从元素中获取文本内容text
str = element.text();
jsoup elements
对象支持类似于CSS (或jquery)
的选择器语法,来实现非常强大和灵活的查找功能。这个select
方法在Document, Element,
或Elements
对象中都可以使用。且是上下文相关的,因此可实现指定元素的过滤,或者链式选择访问。
Select方法将返回一个Elements集合
,并提供一组方法来抽取和处理结果。
1. Selector选择器概述
[attribute]
: 利用属性查找元素,比如:[abc][attr=value]
: 利用属性值来查找元素,比如:[class=s_name]//tagname: 通过标签查找元素,比如:span
Elements span = document.select("span");
for (Element element : span) {
System.out.println(element.text());
}
//#id: 通过ID查找元素,比如:#city_bjj
String str = document.select("#city_bj").text();
//.class: 通过class名称查找元素,比如:.class_a
str = document.select(".class_a").text();
//[attribute]: 利用属性查找元素,比如:[abc]
str = document.select("[abc]").text();
//[attr=value]: 利用属性值来查找元素,比如:[class=s_name]
str = document.select("[class=s_name]").text();
2. Selector选择器组合使用
el#id
: 元素+ID,比如: h3#city_bjel.class
: 元素+class,比如: li.class_ael[attr]
: 元素+属性名,比如: span[abc]ancestor child
: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有liparent > child
: 查找某个父元素下的直接子元素,比如:.city_con > ul > li
查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级liparent > *
: 查找某个父元素下所有直接子元素//el#id: 元素+ID,比如: h3#city_bj
String str = document.select("h3#city_bj").text();
//el.class: 元素+class,比如: li.class_a
str = document.select("li.class_a").text();
//el[attr]: 元素+属性名,比如: span[abc]
str = document.select("span[abc]").text();
//任意组合,比如:span[abc].s_name
str = document.select("span[abc].s_name").text();
//ancestor child: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有li
str = document.select(".city_con li").text();
//parent > child: 查找某个父元素下的直接子元素,
//比如:.city_con > ul > li 查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级li
str = document.select(".city_con > ul > li").text();
//parent > * 查找某个父元素下所有直接子元素.city_con > *
str = document.select(".city_con > *").text();