Java爬虫——抓取静态网页
来源:互联网 发布:淘宝代销经营地址 编辑:程序博客网 时间:2024/05/29 09:08
(2)使用HttpClient发送请求、接收响应的步骤
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请 求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参 数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用 HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接。(关于释放连接,应该不是必须滴,我没处理也抓的好好地。。。)
三、 解析DOM文档
要获取一张网页中我们所需要的内容,就必须解析文档,jsoup就是一款公认的、迄今最强大的解析html的工具
附上具体实现代码:(以此链接为例---https://detail.tmall.com/item.htm?spm=a222t.7794920.fdigt.15.toj3Lg&id=522169321891&skuId=3201261540546&rn=870e70c02239d3cf10b156e9f9aa9e4f&scm=search-api.3c_fp.870e70c02239d3cf10b156e9f9aa9e4f.2)
import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.select.Elements;public class Crawler {public static final int SOCKETTIMEOUT = 30000;public static final int CONNECTTIMEOUT = 30000;private String encode="utf-8";private String url;private CloseableHttpClient client = HttpClientBuilder.create().build();private HttpGet httpGet;private String pageContent = null;private Document doc = null;public String getPageContent() {return pageContent;}public void setPageContent(String pageContent) {this.pageContent = pageContent;}public Document getDoc() {return doc;}public void setDoc(Document doc) {this.doc = doc;}public Crawler(String url) {super();this.url = url;}public HttpGet getNormalHttpGet(){HttpGet httpGet = new HttpGet(this.url);httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;");httpGet.addHeader("Accept-Language", "zh-cn");httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKETTIMEOUT).setConnectTimeout(CONNECTTIMEOUT).build();httpGet.setConfig(requestConfig);return httpGet;}private String convertToThisCharset(String rst){try{String tmp = new String( rst.getBytes(this.encode), "utf-8");return tmp;}catch (Exception e){}return null;}public String run(){HttpResponse response = null;httpGet=getNormalHttpGet();try {response = client.execute(httpGet);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();String respContent = EntityUtils.toString(entity, this.encode).trim();if( !this.encode.equals("UTF-8") )respContent = convertToThisCharset( respContent );return respContent;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{}return null;}public void get(String url)//赋值给this.doc{this.pageContent = run();if (this.pageContent != null){this.doc = Jsoup.parse(this.pageContent);}else{System.out.println( " ... crawled failed.");}}public static void main(String[] args){String url="https://detail.tmall.com/item.htm?spm=a222t.7794920.fdigt.15.toj3Lg&id=522169321891&skuId=3201261540546&rn=870e70c02239d3cf10b156e9f9aa9e4f&scm=search-api.3c_fp.870e70c02239d3cf10b156e9f9aa9e4f.2";Crawler c=new Crawler(url);c.get(url);System.out.println(c.getDoc());Elements price = c.getDoc().select("div.tm-promo-price span.tm-price");if ((price == null) || (price.size() == 0)) {System.out.println("null");}else{System.out.println(price.first().text());}}}运行此代码 会发现天猫价格打印下来为空,这是为什么呢??放心,根据css选择器获取dom元素的代码是没问题哒,之所以获取不到,是因为这个价格是ajax动态加载的,普通的抓取静态网页爬虫抓不下来,此处留一坑 ,下期来补,敬请期待下期——phantomjs抓取ajax动态加载网页。
- Java爬虫——抓取静态网页
- Java抓取网页爬虫
- Java爬虫抓取网页
- Java爬虫——phantomjs抓取ajax动态加载网页
- Java爬虫——phantomjs抓取ajax动态加载网页
- java抓取网页 --- 网络爬虫
- Java爬虫网页抓取图片
- Java实现网络爬虫001-抓取网页
- JAVA使用爬虫抓取网站网页内容
- Python 实现网络爬虫 抓取静态网页【代码】
- Python写爬虫——抓取网页并解析HTML
- Python写爬虫——抓取网页并解析HTML
- Python写爬虫——抓取网页并解析HTML
- Python写爬虫——抓取网页并解析HTML
- Python写爬虫——抓取网页并解析HTML
- Python写爬虫——抓取网页并解析HTML
- python——爬虫实现网页信息抓取
- java抓取网页内容--生成静态页面
- mysql常用命令
- noip模拟赛(一)宠物之战
- mvc从分析到实例,实例到总结
- Java学习总结记录(2)——JVM、JRE和JDK
- 编写SQL语句操作数据库
- Java爬虫——抓取静态网页
- Android进程保活
- CentOS 7 安装天文学工具presto
- Android并发-Future,FutureTask和Callable及AsyncTask
- Android的缓存技术:LruCache和DiskLruCache
- Codeforces 705B.Spider Man
- pip安装lxml时报错
- Find the Difference —— leetcode
- CF #368 D Persistent Bookcase 操作树~?