按照视频中的方法,两次获取list,但是结果还是报错,只能点击一次
来源:6-7 如何通过list去循环课程

qq_醉朴_156
2020-08-10
java代码如下:
package com.mushishi.Imooc;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class ShopsCaseTestng {
public WebDriver driver;
public ArrayList<String> getShopTitles() {
List<WebElement> titleElements = driver.findElements(By.className("shizan-name"));
ArrayList<String> shopTitles = new ArrayList<String>();
for(WebElement element : titleElements) {
String shopTitle = element.getAttribute("innerHTML");
shopTitles.add(shopTitle);
}
return shopTitles;
}
public void initDriver() {
driver = new ChromeDriver();
driver.get("https://www.imooc.com/");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.linkText("实战课程")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
@Test
public void f() {
ArrayList titles = getShopTitles();
for(int i = 0;i<titles.size();i++) {
String title = titles.get(i);
WebElement shopElement = driver.findElement(By.xpath("//p[@title=’"+title+"’]"));
shopElement.click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.navigate().back();
}
}
**/
@Test
public void test1() {
List<WebElement> titleElements = driver.findElements(By.className("shizan-name"));
for(WebElement element : titleElements) {
System.out.println(element.getText());
element.click();
driver.navigate().back();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
titleElements = driver.findElements(By.className("shizan-name"));
}
}
@BeforeMethod
public void beforeMethod() {
}
@AfterMethod
public void afterMethod() {
}
@BeforeClass
public void beforeClass() {
initDriver();
}
@AfterClass
public void afterClass() {
// driver.close();
}
@BeforeTest
public void beforeTest() {
}
@AfterTest
public void afterTest() {
}
}
老师,请问我是按照视频中的方法,两次获取list,但是结果为啥还是一样报错呢?
1回答
-
Mushishi
2020-08-11
你这个错误是当前元素没在当前的dom中。你需要看你的文字中间是不是又两个空格。这里建议xpath。
012020-08-11
相似问题