java selenium 操作谷歌浏览器获取数据

这篇具有很好参考价值的文章主要介绍了java selenium 操作谷歌浏览器获取数据。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

private static ChromeDriver driver;

private static DevTools devTools;

static int count=0;

static {
    System.setProperty("webdriver.chrome.driver", UrlConstant.chromedriver);
    ChromeOptions chromeOptions = new ChromeOptions();
    //chromeOptions.setPageLoadStrategy(PageLoadStrategy.EAGER);
    chromeOptions.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
    //chromeOptions.setBinary("E:\\demo\\Application\\chrome.exe");
    driver = new ChromeDriver(chromeOptions);
    devTools = ((HasDevTools) driver).getDevTools();
    devTools.createSession();
    try {
        cfgChromeTool(driver);
    } catch (Exception e) {
        System.err.println("cfgChromeTool报错:");
    }
}
/**
 * watch the background request
 * */
public static void cfgChromeTool(ChromeDriver driver){
    try {
        //Thread.sleep(10000);// 60秒
        //driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
       // Thread.sleep(10000);// 60秒
    devTools.addListener(Network.responseReceived(), res -> {
        String url = res.getResponse().getUrl();
        if(url.contains(UrlConstant.url_search_count)){
            try {
                String responseBody = devTools.send(Network.getResponseBody(res.getRequestId())).getBody();
                System.out.println("url----------"+url);
                System.out.println("responseBody----------"+ JSON.parseObject(responseBody));
                if(StringUtils.isNoneBlank(responseBody)&&responseBody.contains("nums")){
                    CountVo vo = JSONObject.parseObject(responseBody, CountVo.class);
                    count=vo.getNums();
                }
            } catch (Exception e) {
                System.err.println("转responseBody报错:"+e);
            }
        }
    });
    } catch (Exception e) {
        System.err.println("转responseBody报错:"+e);
    }
}
public static void main(String[] args) throws Exception {
    //BrowserUtil.invoke(BaseVo.builder().name("湘").build());
}
public static void invoke(BaseVo vo) throws Exception{
    System.out.println(DateUtil.getDate()+"--------------开始------------------------"+vo+"-----------------------开始----------------------");

    driver.get(UrlConstant.INDEX_URL);

    operatePage(driver,vo);

}

/**
 * to result page
 * */
public static void operatePage(WebDriver driver, BaseVo vo) throws Exception {
    Thread.sleep(3000);
    //关闭弹窗提示
    By tipABy = By.cssSelector("div.introjs-tooltipbuttons > a.introjs-button");
    waitForLoad(driver, tipABy);
    WebElement tipA = driver.findElement(tipABy);
    tipA.click();

    //点击 医疗器械 标题//直接页面url跳转,如果进首页需要这一步
    //WebElement ylqxBtn = driver.findElement(By.xpath("//i[@class='el-icon-yiliaoqixie']"));
    //ylqxBtn.click();
    //可根据加载网速调整
    //Thread.sleep(1000);

    //点击 搜索框  填写搜索内容
    By searchInputBy = By.cssSelector("div.search-input > input.el-input__inner");
    waitForLoad(driver, searchInputBy);
    WebElement searchInput = driver.findElement(searchInputBy);
    searchInput.clear();
    searchInput.sendKeys(vo.getName());
    //searchInput.click();

    //点击 搜索按钮
    By searchBtnBy = By.cssSelector("div.el-input-group__append > button.el-button");
    waitForLoad(driver, searchBtnBy);
    WebElement searchBtn = driver.findElement(searchBtnBy);
    searchBtn.click();

    //切换标签页
    // 获取所有windowHandle
    Thread.sleep(1000);
    Set<String> windowHandles = driver.getWindowHandles();
    WebDriver.TargetLocator targetLocator = driver.switchTo();
    String handle = "";
    for (String windowHandle : windowHandles) {
        handle = windowHandle;
    }
    // 切换到对应标签页
    targetLocator.window(handle);

    Thread.sleep(3000);//必须否则报错,原因不知道
    //关闭第二页弹窗提示//introjs-tooltipbuttons
    By tipABy2 = By.cssSelector("div.introjs-tooltipbuttons > a.introjs-button");//
    waitForLoad(driver, tipABy2);
    WebElement tipA2 = driver.findElement(tipABy2);
    tipA2.click();

    //点击  第二页 搜索按钮 获取后台请求 UrlConstant.url_search_page
    //Thread.sleep(3000);//必须否则报错,原因不知道
    /*By searchBtnBy2 = By.cssSelector("div.el-input-group__append > button.el-button > i.el-icon-search");//i.el-icon-search   el-button--default
    waitForLoad(driver, searchBtnBy2);
    WebElement searchBtn2 = driver.findElement(searchBtnBy2);
    searchBtn2.click();*/
    //第一页表格数据
    getTable();

    Thread.sleep(1000);
    //计算分页
    By totalBy = By.cssSelector("span.el-pagination__total");//
    waitForLoad(driver, totalBy);
    WebElement totalBySpan = driver.findElement(totalBy);
     String str = totalBySpan.getText();//共 16469 条
    str=str.replace("共","");
    str=str.replace("条","").trim();
    count=Integer.parseInt(str);
    System.out.println("总数count-----一共"+str+"条数");
    int k = count/10;
    int j = count%10;
    if(j>0){
        k=k+1;
    }
    System.out.println("----总页数-----"+k);
    for (int l=2 ;l<=k; l++) {
        clickPage(l);
        Thread.sleep(2000);
        getTable();
        Thread.sleep(3000);
    }
}

public static void clickPage(int pageNum){//当前点击页码pageNum
    //分页
    By pageBtn = By.cssSelector("ul.el-pager > li.number");//滑动验证按钮
    waitForLoad(driver, pageBtn);
    List<WebElement> select = driver.findElements(pageBtn);
    System.out.println(DateUtil.getDate()+"-----clickNextPage——List的长度是:"+select.size());
    for (WebElement page: select) {
        if(String.valueOf(pageNum).equals(page.getText())){
            page.click();
            System.out.println(DateUtil.getDate()+"--------点击翻页按钮:页码是-------"+page.getText());

        }
    }
}

//获取页面数据
public static void getTable() throws InterruptedException {
    //获取table内容
    By tdText = By.cssSelector("div.cell");//div.cell > p
    waitForLoad(driver, tdText);
    List<WebElement> tds = driver.findElements(tdText);
    StringBuffer bf =new StringBuffer();
    int i= 1;
    List<DataVo> l= Lists.newArrayList();
    DataVo v=null;
    for (WebElement td: tds) {
        bf.append(td.getText());bf.append(",");
        if(i%5==1){
            v=new DataVo();
            v.setDesc(td.getText());
            System.out.println(i+"----1---"+td.getText()+"----"+JSON.toJSONString(v));
            Thread.sleep(111);
        }
        i++;
        if(i%5==2){
            System.out.println(i+"----2---"+td.getText()+"----"+JSON.toJSONString(v));
            v.setId(td.getText());
            Thread.sleep(111);
        }
        if(i%5==3){
            System.out.println(i+"----3---"+td.getText()+"----"+JSON.toJSONString(v));
            v.setNum(td.getText());
            Thread.sleep(111);
        }
        if(i%5==4){
            System.out.println(i+"----4---"+td.getText()+"----"+JSON.toJSONString(v));
            v.setRegName(td.getText());
            Thread.sleep(111);
        }
        if(i%5==0){
            System.out.println(i+"----5---"+td.getText()+"----"+JSON.toJSONString(v));
            bf.append(" | ");
            v.setProductName(td.getText());
            l.add(v);
            Thread.sleep(111);
        }
    }
    System.out.println(bf);
    exp(l);
}
/**
* waiting for element loading
 * ***very important***
 * if not do this can't operate web element
* */
public static void waitForLoad(final WebDriver driver, final By by) {
    new WebDriverWait(driver, Duration.ofSeconds(60)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            WebElement element = driver.findElement(by);
            if (element != null) {
                return true;
            }
            return false;
        }
    });
}


public static  Boolean exp(List<DataVo> data){
    try {

        //追加方式写入excel
        File file = new File("/yjj"+DateUtil.getDateYmd()+".xlsx");
        File tempFile = new File("/temp.xlsx");
        if (file.exists()){
            // 第二次按照原有格式,不需要表头,追加写入
            EasyExcel.write(file,DataVo.class).needHead(false).
                    withTemplate(file).file(tempFile).sheet().doWrite(data);
        }else {
            // 第一次写入需要表头
            EasyExcel.write(file,DataVo.class).sheet().doWrite(data);
        }

        if (tempFile.exists()){
            file.delete();
            tempFile.renameTo(file);
        }
    }catch (Exception e){
        System.err.println("excel导出exp报错");
        return false;
    }
    System.out.println("--------excel导出完成------总数: "+count);

    return true;
}

文章来源地址https://www.toymoban.com/news/detail-841305.html

到了这里,关于java selenium 操作谷歌浏览器获取数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • selenium-webdriver调用谷歌浏览器和火狐浏览器

    nodejs selenium-webdriver 操作文档 https://www.npmjs.com/package/selenium-webdriver 1.调用谷歌浏览器 2.调用火狐浏览器 下面设置了一些选项 ​ 需要设置环境变量,在CMD中firefox可以打开浏览器 否则报错 Expected browser binary location, but unable to find binary in default location, no \\\'moz:firefoxOpti  

    2024年02月02日
    浏览(46)
  • 免费 Selenium各大浏览器驱动【谷歌chrme、火狐Firefox、IE浏览器】

    aardio群 625494397 废话不多说 直接开整! 竟然还有脸收费 服了 下载对应版本的浏览器驱动 目标网址 应用场景 Selenium库涉及到 安装selenium库 下载对应浏览器驱动 找到浏览器对应版本 最后直接上代码

    2024年02月16日
    浏览(41)
  • 谷歌浏览器获取网站CA证书

    打开根证书生成网站https://www.myssl.cn/tools/downloadchain.html 将中间证书复制进入框中生成即可

    2024年01月22日
    浏览(55)
  • selenium爬虫,配置谷歌浏览器的driver

    用selenium爬虫时,明明已经安装了selenium模块,程序却运行不了。在使用selenium之前必须先配置浏览器对应版本的webdriver 本文主要涉及 驱动有问题driver   网上有很多手动的方法(查看谷歌浏览的版本然后在其他博主分享的webdriver中下载与自己谷歌版本号最贴近的版本号,并

    2024年02月13日
    浏览(44)
  • 使用python+selenium谷歌浏览器驱动查排名

    这套程序仅供各位同学学习,不作为商业使用工具,该工具包含隐藏浏览器指纹特征,虽然该工具减少了百度弹验证码的频率,但是还是会有一次让手动滑动验证码,作者最后也不知道百度是如何判断模拟器的。 下面介绍使用的扩展有哪些: import time #时间 from selenium import

    2024年02月11日
    浏览(46)
  • Selenium 远程调用 Google Chrome 谷歌浏览器

    我最近又使用谷歌浏览远程调用发现不能使用了 参考连接 具体原因是因为 谷歌浏览器在11几的版本(目前是:114.0.5735.91)之后只能使用JDK高版本我目前使用的是JDK17版本远程调用如果是低版本比如102左右的是好使的,新使用方法我更新在下面 一. 前沿 每次重新运行Selenium都直接弹

    2024年02月10日
    浏览(37)
  • python用selenium模拟谷歌浏览器点页面

    1、cmd安装selenium,输入pip install selenium 2、模拟点击热搜第一条进去,连接如下 https://weibo.com/newlogin?tabtype=weibogid=102803openLoginLayer=0url=https%3A%2F%2Fweibo.com%2F 3、查看谷歌版本   4、并去下面下载对应版本的webdriver,解压后把chromedriver.exe放入python目录 CNPM Binaries Mirror https://regist

    2024年01月21日
    浏览(35)
  • selenium 加载带有插件的谷歌浏览器 option

    selenium做自动化时,每次启动都是一个干净的浏览器,这时候可以用自带的option来实现,代码如下: 还可以直接加载Chrome用户数据: 注:crx地址可以通过【打包扩展程序】获取

    2024年02月13日
    浏览(35)
  • Python--使用selenium通过chromedriver调用谷歌浏览器

    原文网址:Python--使用selenium通过chromedriver调用谷歌浏览器_IT利刃出鞘的博客-CSDN博客         本文用实例介绍Python如何使用selenium通过chromedriver调用谷歌浏览器。 谷歌浏览器访问:chrome://version/ 注意:通过【帮助= 关于Google Chrome 】这种方式来查看会导致谷歌浏览器自动更新

    2023年04月21日
    浏览(82)
  • 谷歌浏览器驱动的安装及selenium的安装与使用

    在爬虫时,常常会使用selenium模块,本文演示如何下载安装谷歌浏览器驱动以及安装selenium及基本使用。 步骤总结: 下载安装selenium 下载安装谷歌浏览器驱动 selenium的基础使用 附其他浏览器驱动的下载链接 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解

    2024年02月06日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包