【Jsoup in action】模拟浏览器:Jsoup工具类的使用及失败重试的retry策略(三)

时间:2022-10-31 09:38:39
从一个URL获取Document对象的其他姊妹章:

模拟浏览器:get方式简单获取网页数据(一)
模拟浏览器:post方式模拟登陆获取网页数据(二)
模拟浏览器:Jsoup工具类的使用及失败重试的retry策略(三)

工具类:顾名思义是一个工具,作为工具就是给别人使用的,只提供静态方法的无状态类(通常以Helper和Util(s)结尾),它没有明确的业务职能,在项目中也不会被实例化成对象。
在实际做爬虫中,访问不同的网站或者同一网站不同的地址的时候,会创建不同Jsoup Connection,这样会造成代码的大量重复逻辑,
将创建connection的过程封装成util工具类,很好的解决了此类问题。
一般爬虫都是在做无人值守,很多的网站也会有反爬虫策略,这样你做的爬虫很有可能再正常执行一段时间后就出现了问题,下面的工具类提供了简单的retry失败重试策略,在项目中retry策略可以更加丰富,比如追加动态代理,随记访问时间等。
/**
* En:Utils class to parse website html by <code>Jsoup</code></br>
* Jp:ウェブサイトを解析する用ユーティリティクラス</br>
* Zh:Jsoup模拟浏览器解析网页工具类</br>
*
* @since crawler(datasnatch) version(1.0)</br>
* @author bluetata / https://github.com/bluetata</br>
* @version 1.0</br>
*
*/
public final class JsoupUtil {
/**
* 方法用途和描述: 模拟浏览器以Document类型返回被访问的网站源码
*
* @param url 被访问的website. 所传的URL必须以 "http://www."开头
* @return doc 以Document类型返回被访问网页的html
* @throws Exception
*/
public static Document getDocument(String url) throws Exception {

Document doc = null;
StringWriter strWriter = new StringWriter();
PrintWriter prtWriter = new PrintWriter(strWriter);

// En:get max retry count from properties file(com-constants.properties)
// Jp:プロパティファイルでロックタイムアウトのリトライ回数を取得する Zh:通过properties获取最大retry次数
int maxRetry = Integer.parseInt(PropertyReader.getProperties(SystemConstants.COM_CONSTANTS)
.getProperty(UtilsConstants.MAX_RETRY_COUNT));
// En: get sleep time from properties file Jp:プロパティファイルでロックタイムアウトのスリープ時間を取得する
int sleepTime = Integer.parseInt(PropertyReader.getProperties(SystemConstants.COM_CONSTANTS)
.getProperty(UtilsConstants.SLEEP_TIME_COUNT));

// En: if exception is occurred then retry loop is continue to run;
// Jp: 異常を起きる場合、ループを続き実行する。
for (int j = 1; j <= maxRetry; j++) {

try {
if (j != 1) {
Thread.sleep(sleepTime);
}
doc = Jsoup.connect(url).timeout(10 * 1000)
.userAgent(
// add userAgent. TODO There is a plan to configure userAgent to load that userAgent from a property file.
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30")
.get();

// En: normal finish situation,loop is broken.
// Jp: サービスが正常に終了した場合、ループを中止します。
// Zh: 正常终了的情况、终止循环。
break;

} catch (Exception ex) {
// throw new Exception(ex); dead code is occurred

// StackTraceを文字列で取得
ex.printStackTrace(prtWriter);
String stackTrace = strWriter.toString();

if (strWriter != null) {
try {
strWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (prtWriter != null) {
prtWriter.close();
}

// En:info log is output. Jp: Infoログとして、エラー内容を出力。 Zh:输出到info log。
Log4jUtil.info(stackTrace);
}
}
return doc;
}
}

Jsoup学习讨论QQ群:50695115

Jsoup爬虫代码示例及博客内源码下载:https://github.com/bluetata/crawler-jsoup-maven

更多Jsoup相关文章,请查阅专栏:【Jsoup in action】


本文原创由`bluetata`发布于blog.csdn.net、转载请务必注明出处。


【Jsoup in action】模拟浏览器:Jsoup工具类的使用及失败重试的retry策略(三)