数据挖掘之网络爬虫 - 基础

原作者文章地址: https://yq.aliyun.com/articles/655873
在项目添加 maven 配置

<!-- 解析数据 -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.8.3</version>
</dependency>

<!-- 爬网页 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

使用 HttpClient 发起请求获取页面数据

HttpGet httpGet = new HttpGet("https://www.baidu.com/");

HttpHost proxy = new HttpHost("125.70.13.77", 8080);// 使用代理服务器发送请求
httpGet.setConfig(RequestConfig.custom()
                  .setSocketTimeout(30000)// 发送时间
                  .setConnectTimeout(30000)// 连接时间
                  .setProxy(proxy)// 设置代理服务器
                  .build());

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpClientContext context = HttpClientContext.create();

CloseableHttpResponse response = httpClient.execute(httpGet, context);

HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity, "utf-8");

System.out.println(html);
  1. 不使用本机发起请求, 而是使用代理服务器发起请求是应为: 防止被一些反扒网站拉黑: 代理服务器

使用Jsoup发起请求并且解析页面数据

// 获取 Document 对象
Document document = Jsoup.connect("https://www.baidu.com/").get();

// 通过 CSS 选择器, 匹配标签数据
Elements select = document.select("a");

for (Element element : select) {
    System.out.println(element);
}
  1. Document对象中有各种JavaScript 和 CSS解析方法

一般发送请求使用httpclient解析网页数据使用jsoup, 两者组合使用

HttpGet httpGet = new HttpGet("https://www.baidu.com/");

HttpHost proxy = new HttpHost("125.70.13.77", 8080);
httpGet.setConfig(RequestConfig.custom()
                  .setSocketTimeout(30000)
                  .setConnectTimeout(30000)
                  .setProxy(proxy)
                  .build());

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpClientContext context = HttpClientContext.create();

CloseableHttpResponse response = httpClient.execute(httpGet, context);

HttpEntity entity = response.getEntity();
String htmlData = EntityUtils.toString(entity, "utf-8");

Document document = Jsoup.parse(htmlData);

Elements select = document.select("a");

for (Element element : select) {
    System.out.println(element);
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值