• WebDriver+PhantomJs爬虫运用(Java)


    需要的添加的jar包及工具:我这里使用maven来构建项目,添加依赖如下:

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.2.0</version>
    </dependency>  

    PhantomJs工具到官网去下载:http://phantomjs.org/download.html

    尽量都使用最新版本,不然会出现版本兼容的情况。

    这里有一个已经写好的获取PhantomJSDriver的工具类

    public static WebDriver getPhantomJs() {
      String osname = System.getProperties().getProperty("os.name");
      if (osname.equals("Linux")) {//判断系统的环境win or Linux
        System.setProperty("phantomjs.binary.path", "/usr/bin/phantomjs");
      } else {
        System.setProperty("phantomjs.binary.path", "./phantomjs/win/phantomjs.exe");//设置PhantomJs访问路径
      }
      DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
      //设置参数
      desiredCapabilities.setCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
      desiredCapabilities.setCapability("phantomjs.page.customHeaders.User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101   Firefox/50.0");
      if (Constant.isProxy) {//是否使用代理
        org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
        proxy.setProxyType(org.openqa.selenium.Proxy.ProxyType.MANUAL);
        proxy.setAutodetect(false);
        String proxyStr = "";
        do {
          proxyStr = ProxyUtil.getProxy();//自定义函数,返回代理ip及端口
        } while (proxyStr.length() == 0);
        proxy.setHttpProxy(proxyStr);
        desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
      }
      return new PhantomJSDriver(desiredCapabilities);
    }

    获取方式  

      try{
        WebDriver webDriver = PhantomJsUtil.getPhantomJs();
        webDriver.get(url);
        SleepUtil.sleep(Constant.SEC_5);
        PhantomJsUtil.screenshot(webDriver);
        WebDriverWait wait = new WebDriverWait(webDriver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.id(inputId)));//开始打开网页,等待输入元素出现
        Document document = Jsoup.parse(webDriver.getPageSource());

        //TODO  剩下页面的获取就按照Jsoup获取方式来做

      }finally{
        if (webDriver != null) {
          webDriver.quit();
        }
      }

    python版使用webdriver+PhantomJs爬虫使用,参考http://www.cnblogs.com/kuqs/p/6395284.html

  • 相关阅读:
    DAS,NAS,SAN在数据库存储上的应用
    ASP.NET4.5Web API及非同步程序开发系列3
    WCFRESTFul服务搭建及实现增删改查
    Workflow:自定义工作流 之 模型选择
    结构变量作为方法的参数调用
    C语言复习笔记-17种小算法-解决实际问题
    构建RESTful风格的WCF服务
    进程状态转换、CPU调度算法
    Excel 开发概述
    jQuery 1.10.2 and 2.0.3 Released
  • 原文地址:https://www.cnblogs.com/shirandedan/p/6802763.html
Copyright © 2020-2023  润新知