项目需要爬 http://www.cnvd.org.cn/,发现每次都是521失败,返回的结果是一段JS代码。于是开始各种度娘。原来这段JS代码是生成一个参数并放到cookie中,然后重新发送一次请求,这样第二次请求就能带上这个参数以及上次请求返回的cookie信息,到后台进行验证。原因知道了,但是问题并没有解决。返回的JS代码用了很多乱七八糟的符号替换来替换去,有人说是在加密,反正我没看懂.....但是大致的东西看懂了一些。通过fidder可以观察到使用浏览器访问时其实是发送了两次请求,
第一次请求拿到的结果如下:
<script>
var x="try@charAt@Tue@g@1497962429@while@window@document@cookie@_phantom@40@UkGE@EP@join@GMT@if@for@Jun@1500@function@0@06@DOMContentLoaded@17@29@return@F@Expires@13@S@captcha@l@ZxX@length@orders@D@cd@3@addEventListener@setTimeout@2@20@replace@4@href@onreadystatechange@challenge@e@else@location@8@SG@dc@var@__phantomas@i@false@Path@__jsl_clearance@catch@attachEvent@PP@R@Array".replace(/@*$/,"").split("@"),
y="1e w=k(){6(7.a||7.1f){};1e B,1d='1j=5.m|l|';1e z=[[-~[]]+(1b+[]),[-~[]]+(11+[[], []][(+[])]),[(+!+[])+(+!+[])+(+!+[])+(+!+[])],[((+!+[])<<(+!+[]))+(+!+[])+(+!+[])+(+!+[])],[-~[]+[~~{}]-(-~[])],[-~[]]+[((+!+[])<<(+!+[]))+(+!+[])+(+!+[])+(+!+[])],(((+!+[])+[-~((+!+[])+(+!+[])+(+!+[]))]>>(+!+[]))+[]),(~~[]+[]+[]),[-~[]]+[-~[]],[(+!+[])+([((+!+[])<<(+!+[]))]+~~[]>>((+!+[])<<(+!+[])))],(11+[[], []][(+[])]),[-~[]]+(C+[]+[[]][~~!{}]),(1b+[]),[-~[]]+(~~[]+[]+[]),(C+[]+[[]][~~!{}]),[-~[]],[-~[]]+[(+!+[])+(+!+[])+(+!+[])+(+!+[])],[-~[]]+[(+!+[])+([((+!+[])<<(+!+[]))]+~~[]>>((+!+[])<<(+!+[])))],[-~[]]+(((+!+[])+[-~((+!+[])+(+!+[])+(+!+[]))]>>(+!+[]))+[])];B=1o(z.y);h(1e 1g=l;1g<z.y;1g++){B[z[1g]]=['A','r','1m',[!-[]+[]+[]][l].2(-~!{}),[[(+!+[])+(+!+[])]/(+[])+[[]+[[]][~~!{}], []][-~{}]][l].2(14),({}+[[], []][(+[])]).2((-~-~{}^-~{}))+(![]+[[], []][(+[])]).2((+!+[])+(+!+[]))+[+[-~{}, -~{}]+[]+[]][l].2((+!+[])+(+!+[])),(~~[]+[]+[]),'x',(11+[[], []][(+[])]),'u','1c',[{}+[]][l].2(((+!+[])<<(+!+[]))),'4','d%',(!~~!{}+[[]+[[]][~~!{}], []][-~{}]).2(~~[]),[[(+!+[])+(+!+[])]/(+[])+[[]+[[]][~~!{}], []][-~{}]][l].2(14)+(!~~!{}+[[]+[[]][~~!{}], []][-~{}]).2(~~[]),'1n','c%',(C+[]+[[]][~~!{}])][1g]};B=B.e('');1d+=B;10('1a.15=1a.15.13(/[\\?|&]v-17/,\\'\\')',j);8.9=(1d+';s=3, 12-i-o t:b:p f;1i=/;');};g((k(){1{q !!7.D;}1k(18){q 1h;}})()){8.D('n',w,1h);}19{8.1l('16',w);}",
z=0,f=function(x,y){var a=0,b=0,c=0;x=x.split("");y=y||99;while((a=x.shift())&&(b=a.charCodeAt(0)-77.5))c=(Math.abs(b)<13?(b+48.5):parseInt(a,36))+y*c;return c},
g=y.match(/\b\w+\b/g).sort(function(x,y){return f(x)-f(y)}).pop();
while(f(g,++z)-x.length){};
eval(y.replace(/\b\w+\b/g, function(y){return x[f(y,z)-1]}));
</script>
这是整理后的,原本只有一行。第二次请求:前这样就发现第二次请求在cookie中多了一个__jsl_clearance参数。这个参数哪来的呢,看第一几次请求返回的JS代码。面声明了一大堆变量,只关注最后最后一句即可,将字符串转为可执行的JS代码,那这个字符串是什么,只需将这段代码拿到html文件中用浏览器执行下就知道了,如下
var l=function(){
while(window._phantom||window.__phantomas){};
var cd,dc='__jsl_clearance=1497962429.06|0|';
var orders=[[-~[]]+(8+[]),[-~[]]+(2+[[], []][(+[])]),[(+!+[])+(+!+[])+(+!+[])+(+!+[])],[((+!+[])<<(+!+[]))+(+!+[])+(+!+[])+(+!+[])],[-~[]+[~~{}]-(-~[])],[-~[]]+[((+!+[])<<(+!+[]))+(+!+[])+(+!+[])+(+!+[])],(((+!+[])+[-~((+!+[])+(+!+[])+(+!+[]))]>>(+!+[]))+[]),(~~[]+[]+[]),[-~[]]+[-~[]],[(+!+[])+([((+!+[])<<(+!+[]))]+~~[]>>((+!+[])<<(+!+[])))],(2+[[], []][(+[])]),[-~[]]+(3+[]+[[]][~~!{}]),(8+[]),[-~[]]+(~~[]+[]+[]),(3+[]+[[]][~~!{}]),[-~[]],[-~[]]+[(+!+[])+(+!+[])+(+!+[])+(+!+[])],[-~[]]+[(+!+[])+([((+!+[])<<(+!+[]))]+~~[]>>((+!+[])<<(+!+[])))],[-~[]]+(((+!+[])+[-~((+!+[])+(+!+[])+(+!+[]))]>>(+!+[]))+[])];cd=Array(orders.length);
for(var i=0;i<orders.length;i++){
cd[orders[i]]=['D','F','PP',[!-[]+[]+[]][0].charAt(-~!{}),[[(+!+[])+(+!+[])]/(+[])+[[]+[[]][~~!{}], []][-~{}]][0].charAt(4),({}+[[], []][(+[])]).charAt((-~-~{}^-~{}))+(![]+[[], []][(+[])]).charAt((+!+[])+(+!+[]))+[+[-~{}, -~{}]+[]+[]][0].charAt((+!+[])+(+!+[])),(~~[]+[]+[]),'ZxX',(2+[[], []][(+[])]),'S','SG',[{}+[]][0].charAt(((+!+[])<<(+!+[]))),'g','EP%',(!~~!{}+[[]+[[]][~~!{}], []][-~{}]).charAt(~~[]),[[(+!+[])+(+!+[])]/(+[])+[[]+[[]][~~!{}], []][-~{}]][0].charAt(4)+(!~~!{}+[[]+[[]][~~!{}], []][-~{}]).charAt(~~[]),'R','UkGE%',(3+[]+[[]][~~!{}])][i]
};
cd=cd.join('');
dc+=cd;
setTimeout('location.href=location.href.replace(/[\?|&]captcha-challenge/,\'\')',1500);
document.cookie=(dc+';Expires=Tue, 20-Jun-17 13:40:29 GMT;Path=/;');
};
if((function(){try{return !!window.addEventListener;}catch(e){return false;}})()){
document.addEventListener('DOMContentLoaded',l,false);
}else{
document.attachEvent('onreadystatechange',l);
}
这就清晰了许多,if语句是执行方法1的。方法里 setTimeout 是刷新页面重新发送一次请求,document.cookie 是向cookie中添加 dc这个参数。如果能拿到dc的值,添加到我们自己的java代码里岂不是可以再请求一次就能拿到页面的html代码了。思路已然很清晰,问题是如何在java代码中执行JS代码呢?答案是 J2V8。
使用将 j2v8只需引入所需jar包即可,不同的操作系统需要的jar包不同,去maven库选择对应的版本添加依赖即可。
<dependency>
<groupId>com.eclipsesource.j2v8</groupId>
<artifactId>j2v8_win32_x86_64</artifactId>
<version>4.6.0</version>
</dependency>
测试下j2v8,示例
public static void main(String[] args) {
//创建JS代码运行环境
V8 runtime = V8.createV8Runtime();
//执行JS代码,根据返回值类型不同,选择不同的执行方法
String result=runtime.executeStringScript(
"var hello='hello ';var world='world !'; hello.concat(world);");
System.out.println(result);
//释放运行环境
runtime.release();
}
输出结果:hello world ! ,其它具体的使用可继续百度和Google 。
后面就是通过java代码先模拟浏览器拿到第一次请求返回的Js代码,再根据具体的代码逻辑拿到想要的参数,放入cookie中进行第二次访问,拿到最后的html内容。示例代码:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.eclipsesource.v8.V8;
public class TestJ2V8 {
public static void main(String[] args) throws ClientProtocolException, IOException {
String url="http://www.cnvd.org.cn/flaw/show/CNVD-2017-10268";
CloseableHttpClient client = HttpClients.createDefault();
//设置代理
HttpHost proxy = new HttpHost("192.167.5.13", 808, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet get=new HttpGet(url);
//模拟浏览器
get.setConfig(config);
get.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
get.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
get.setHeader("Accept-Encoding", "gzip, deflate");
get.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
get.setHeader("Connection", "keep-alive");
get.setHeader("Host", "www.cnvd.org.cn");
get.setHeader("referer", "http://www.cnvd.org.cn/");
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
CloseableHttpResponse response = client.execute(get);
//拿到第一次请求返回的JS
if(response.getStatusLine().getStatusCode()==521){
HttpEntity entity = response.getEntity();
String html=EntityUtils.toString(entity,"utf-8");
System.out.println(html);
//处理从服务器返回的JS,并执行
String js=html.trim().replace("<script>", "").replace("</script>", "").replace("eval(y.replace(/\\b\\w+\\b/g, function(y){return x[f(y,z)-1]}))","y.replace(/\\b\\w+\\b/g, function(y){return x[f(y,z)-1]})");
V8 runtime = V8.createV8Runtime();
String result=runtime.executeStringScript(js);
System.out.println(result);
//第二次处理JS并执行
result=result.substring(result.indexOf("var cd"),result.indexOf("dc+=cd;")+7)+" dc;";
System.out.println(result);
String __jsl_clearance=runtime.executeStringScript(result);
System.out.println(__jsl_clearance);
runtime.release();
get.setHeader("Cookie",__jsl_clearance);
response=client.execute(get);
}
//拿到最终想要的页面
HttpEntity entity = response.getEntity();
String res=EntityUtils.toString(entity,"utf-8");
System.out.println(res);
}
}
总结:1、对于爬虫返回521,每个网站原因是不一样的,有的可能只是对请求头信息验证不通过,有的是对cookie验证等等,具体得通过工具查看浏览器是如何访问的,模仿浏览器访问。
2、对于返回JS代码的,每个网站的代码逻辑也不同,需要具体对待,但最终都是生成参数用于第二次请求,也有的会在第一次响应头加入一些参数需要再第二次请求也带上的,都需要注意。
后续补充:
最近发现CNVD又不能爬了,分析了下是第一次返回的脚本规则改了,新的脚本需要用到浏览器内核元素,V8不支持。改用selenium,使用如下
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.52.0</version>
</dependency>
public class TestSelenium {
public static void main(String[] args) {
HtmlUnitDriver driver = new HtmlUnitDriver();
//必须设置为true,才能执行js代码
driver.setJavascriptEnabled(true);
driver.get("http://www.cnvd.org.cn/");
/*Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie cookie:cookies){
System.out.println(cookie);
}*/
driver.setJavascriptEnabled(false);
driver.get("http://www.cnvd.org.cn/flaw/show/CNVD-2017-30496");
String pageSource = driver.getPageSource();
System.out.println(pageSource);
}
}