2015-12-21 87 views
0

我正在尝试查找所有继续阅读在随机的Facebook页面中,并在新选项卡中打开它们。查找并点击所有具有相同定位符的webelements

首先找到包含继续阅读后,打开新的标签页,之后的一些动作在打开一个新标签页面完成,它会关闭,然后找到第二继续读书后,如果有的话,在新标签中打开,执行一些操作并关闭,继续处理,直到没有更多继续阅读帖子。

下面的代码是我为实现上述目的而写的。

List <WebElement> continuereading = driver.findElements(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]")); 

    System.out.println(continuereading); 
    for (int i=0; i <= continuereading.size(); i++){ 
     //check if there is continue reading element in post 
     if (continuereading.size() > 0) { 
      WebElement contreading = driver.findElement(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]")); 

      //open link in new tab 
      Actions action = new Actions(driver); 
      action.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform(); 
      //scroll to the element 
      jse.executeScript("arguments[0].scrollIntoView(true);", contreading); 
      contreading.click(); 
      action.keyUp(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform(); 

      //close new tab 
      action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform(); 
      action.keyUp(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform(); 

     } 
    } 

问题由于继续阅读元素点击后不会消失,第一个元素被连续点击,并在一个新的标签,直到循环结束开通,而其他继续阅读要素根本不被点击。

有没有办法解决这个问题,将使所有的继续阅读元素被发现和点击?

+0

我不知道'Java'的具体情况,但是在'Python'中,continuereading'变量是元素列表。并且每个元素都可以通过它的索引来调用,而不是通过'driver.findElement()'方法调用它的索引:“继续读[0]”,“继续读[1]”(在'循环中继续读[i] ... – Andersson

回答

0

这是因为在for循环内部,您将再次获取该元素。

WebElement contreading = driver.findElement(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]")); 

这种特殊的线总是会得到你的页面上的第一个元素,并点击它(您遇到什么)。 相反,只是做:

for (int i=0; i < continuereading.size(); i++){ 
    //open link in new tab 
      Actions action = new Actions(driver); 
      action.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform(); 
      //scroll to the element 
      jse.executeScript("arguments[0].scrollIntoView(true);", continuereading.get(i)); 
      continuereading.get(i).click(); 
      action.keyUp(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform(); 

      //close new tab 
      action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform(); 
      action.keyUp(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform(); 

     } 

请注意,我也修正了自己的for循环迭代。你从0迭代到list.size()包括,这将最终抛出和IndexOutOfBoundsException

相关问题