Selenium webdriver滚动加载页面的爬取

发表于:2019-6-28 16:41

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:风一样的存在    来源:简书

分享:
  场景:滚动滚动条页面的元素在加载,有时候会出现一个加载更多的按钮,点击后继续加载(googleplay应用市场app信息页面)
  安装的app信息
  具体代码实现:
   /**
  * 滚动页面到指定位置
  * @param context
  * @throws Exception
  */
  private void crawlApps(TaskContext context){
  WebDriver webDriver = context.getWebDriver();
  WebElement element;
  JavascriptExecutor jsExecutor=(JavascriptExecutor) webDriver;
  boolean flag = true;
  Actions actions = new Actions(webDriver);
  long checkHeight =  (Long) jsExecutor.executeScript("return document.body.scrollHeight;");
  while (flag){
  //每次滚动固定像素
  jsExecutor.executeScript("window.scrollBy(0,document.body.scrollHeight)");
  long nextHeight =  (Long)jsExecutor.executeScript("return document.body.scrollHeight;");
  if (nextHeight > checkHeight){
  checkHeight =  (Long)jsExecutor.executeScript("return document.body.scrollHeight;");
  //查找是否含有加载更多的按钮
  if (expectBy(context,By.xpath(XPATH_SHOW_MORE),5)) {
  element = webDriver.findElement(By.xpath(XPATH_SHOW_MORE));
  actions.moveToElement(element).build().perform();
  click(context,By.xpath(XPATH_SHOW_MORE));
  }
  }
  else{
  flag = false;
  }
  //actions.sendKeys(Keys.PAGE_DOWN).perform();
  }
  }
  /**
  * 期望出现的元素
  * @param context
  * @param by
  * @param seconds
  * @return 元素是否出现
  */
  protected boolean expectBy(TaskContext context, By by, long seconds) {
  try {
  (new WebDriverWait(context.getWebDriver(), seconds)).until(ExpectedConditions.elementToBeClickable(by));
  return true;
  } catch (Exception e) {
  return false;
  }
  }
  
      不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号