htmlunit教程 动态链接的获取

<pre class="prettyprint cs" style="margin-top: 0px; margin-bottom: 1.5em; padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; color: rgb(51, 51, 51); border-radius: 4px; line-height: 1.5em; word-break: break-all; word-wrap: break-word; white-space: pre-wrap; border: 1px solid rgba(0, 0, 0, 0.14902); overflow-y: auto; background-color: rgb(246, 246, 246);"><pre name="code" class="java">String  url="http://news.cnblogs.com/";//想采集的网址
  String refer="http://www.cnblogs.com/";
  URL link=new URL(url); 
  WebClient wc=new WebClient();
  WebRequest request=new WebRequest(link); 
  request.setCharset("UTF-8");
  request.setProxyHost("120.120.120.x");
  request.setProxyPort(8080);
  request.setAdditionalHeader("Referer", refer);//设置请求报文头里的refer字段
  ////设置请求报文头里的User-Agent字段
  request.setAdditionalHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
  //wc.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
  //wc.addRequestHeader和request.setAdditionalHeader功能应该是一样的。选择一个即可。
  //其他报文头字段可以根据需要添加
  wc.getCookieManager().setCookiesEnabled(true);//开启cookie管理
  wc.getOptions().setJavaScriptEnabled(true);//开启js解析。对于变态网页,这个是必须的
  wc.getOptions().setCssEnabled(true);//开启css解析。对于变态网页,这个是必须的。
  wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
  wc.getOptions().setThrowExceptionOnScriptError(false);
  wc.getOptions().setTimeout(10000);
  //设置cookie。如果你有cookie,可以在这里设置
  Set<Cookie> cookies=null;
  Iterator<Cookie> i = cookies.iterator();
  while (i.hasNext()) 
  {
      wc.getCookieManager().addCookie(i.next());
  }
  //准备工作已经做好了
  HtmlPage page=null;
  page = wc.getPage(request);
  if(page==null)
  {
      System.out.println("采集 "+url+" 失败!!!");
      return ;
  }
  String content=page.asText();//网页内容保存在content里
  if(content==null)
  {
      System.out.println("采集 "+url+" 失败!!!");
      return ;
  }
  //搞定了
  CookieManager CM = wc.getCookieManager(); //WC = Your WebClient's name
  Set<Cookie> cookies_ret = CM.getCookies();//返回的Cookie在这里,下次请求的时候可能可以用上啦。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章