Chinaunix首页 | 论坛 | 博客
  • 博客访问: 125643
  • 博文数量: 46
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2014-07-19 19:13
文章分类

全部博文(46)

文章存档

2015年(1)

2014年(45)

我的朋友

分类: Java

2014-10-29 11:50:55

最近写了个爬虫项目,暂时放在github上。

 

对于爬虫最难的问题应该是javascript和ajax的处理。现在很多网站使用大量ajax,普通爬虫无法获取js生成的

内容。

 

目前大体上有2中方式来解决这个问题。

一是使用htmlunit之类的所谓handless browser。htmlunit对js支持相当不错。只是适用起来不很方便。想要知道什么时候js执行完了比较困难。

官网 FQA对这个问题的说明。

 

 

Nothing happens when using HtmlUnit with AJAX, although page works correctly in browsers. What's wrong?

The main thread using HtmlUnit may be finishing execution before allowing background threads to run. You have a couple of options:

  1. webClient.setAjaxController(new NicelyResynchronizingAjaxController()); will tell your WebClient instance to re-synchronize asynchronous XHR.
  2. webClient.waitForBackgroundJavaScript(10000); or webClient.waitForBackgroundJavaScriptStartingBefore(10000); just after getting the page and before manipulating it.
  3. Explicitly wait for a condition that is expected be fulfilled when your JavaScript runs, e.g.
            //try 20 times to wait .5 second each for filling the page.
            for (int i = 0; i < 20; i++) {
                if (condition_to_happen_after_js_execution) {
                    break;
                }
                synchronized (page) {
                    page.wait(500);
                }
            }

我的测试:

Java代码  收藏代码
  1. public static void testYouku() throws Exception {  
  2.         String url = "";  
  3.         String xurl = "";  
  4.         // String a = "178-101";  
  5.         // String url="";  
  6.         // 模拟一个浏览器  
  7.         final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);  
  8.   
  9.         LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");  
  10.         java.util.logging.Logger.getLogger("net.sourceforge.htmlunit").setLevel(java.util.logging.Level.OFF);  
  11.         webClient.getOptions().setThrowExceptionOnScriptError(false);  
  12.         webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);  
  13.         // final WebClient webClient=new  
  14.         // WebClient(BrowserVersion.FIREFOX_10,"",8000);  
  15.         // //使用代理  
  16.         // final WebClient webClient2=new  
  17.         // WebClient(BrowserVersion.INTERNET_EXPLORER_10);  
  18.         // 设置webClient的相关参数  
  19.         webClient.getOptions().setJavaScriptEnabled(true);  
  20.         webClient.getOptions().setActiveXNative(false);  
  21.         webClient.getOptions().setCssEnabled(false);  
  22.         webClient.getOptions().setThrowExceptionOnScriptError(false);  
  23.         webClient.waitForBackgroundJavaScript(600*1000);  
  24.         webClient.setAjaxController(new NicelyResynchronizingAjaxController());  
  25.           
  26.         webClient.getOptions().setJavaScriptEnabled(true);    
  27.         /* 
  28.         webClient.setJavaScriptTimeout(3600*1000);   
  29.         webClient.getOptions().setRedirectEnabled(true);   
  30.         webClient.getOptions().setThrowExceptionOnScriptError(true);   
  31.         webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);   
  32.         webClient.getOptions().setTimeout(3600*1000);   
  33.         webClient.waitForBackgroundJavaScript(600*1000);   
  34.         */  
  35. //      webClient.waitForBackgroundJavaScript(600*1000);  
  36.         webClient.setAjaxController(new NicelyResynchronizingAjaxController());   
  37.           
  38.         // 模拟浏览器打开一个目标网址  
  39.         final HtmlPage page = webClient.getPage(url);  
  40. //      该方法在getPage()方法之后调用才能生效  
  41.         webClient.waitForBackgroundJavaScript(1000*3);  
  42.         webClient.setJavaScriptTimeout(0);  
  43. //      Thread.sleep(1000 *3L);  
  44. //      String js = "javascript:checkShowFollow('271942','2');";  
  45. //      ScriptResult sr = page.executeJavaScript(js);  
  46. //      HtmlPage newPage = (HtmlPage) sr.getNewPage();  
  47. //      System.out.println("new page.asText=" + newPage.asText());  
  48. //      System.out.println("page.asText=" + page.asText());  
  49. //      System.out.println("page.getUrl=" + page.getUrl());  
  50.         List links = (List) page.getByXPath ("//*[@id=\"groups_tab\"]/div[1]/ul/li[1]/a");  
  51.         if(null!=links){  
  52.             System.out.println(links.size());  
  53.             HtmlAnchor link = (HtmlAnchor) links.get(0);  
  54.             System.out.println(link.asXml());  
  55.             HtmlPage p = link.click();  
  56.             webClient.waitForBackgroundJavaScript(1000*3L);  
  57. //          webClient.waitForBackgroundJavaScriptStartingBefore(1000L);  
  58. //          Thread.sleep(3000L);  
  59.             System.out.println(p.asText());  
  60.         }  
  61.     }  

 youku上面超过100集会拆分多个列表展示,全部是js生成的。

 

上面代码执行的成功率不是很高。

 

2013.12.05 19:25:58 Re-synchronized call to

2013.12.05 19:26:00 Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at ' /html?p=74,75,558,747,753,850,101618,616,101564&ct=h& cs=2224|2210|2209&td=0&s=271942&v=119023280&u=83980375& amp;k=%E7%BD%91%E7%90%83%E7%8E%8B%E5%AD%90|&sid=1386242750138i0r& amp;tt=网球王子 001&pu=&ref=', but got 'text/html'.

 

其实只要能拿到Re-synchronized call to后面的URL后直接使用httpclient就可以了。但是htmlunit没有提供相关方法。debug了一下源码还是没找到什么时候这个URL被生成的(这个URL肯定是js函数中生成并异步调用的)。

 

继续研究。。。

 

第二种方法是使用selenium,jdic直接调用浏览器。

 

这两种方式都太慢。相对来说第一种方式效率比第二种要好一些。


阅读(1500) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~