遍历课程列表代码。

public void test02() {
List<Integer> numList = PageNumList();//将PageNumList()方法中获取到的页码放入list集合,一页一页循环出来
for (int j = 0; j < numList.size() - 1; j++) {
//根据元素定位到所有课程名称并放到list集合
List<WebElement> courseList = driver.findElements(By.className("shizan-name"));
for (int i = 0; i < courseList.size(); i++) {
courseList.get(i).click();//点击获取到的课程名
driver.navigate().back();//返回
try {
Thread.sleep(2);
} catch (InterruptedException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.className("js-close")).click();
// 返回之后页面刷新了,所以要给courseList重新赋值,再次进行循环才能正确定位到元素
courseList = driver.findElements(By.className("shizan-name"));
}
driver.findElement(By.linkText("下一页")).click();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

// 获取页码
public List<Integer> PageNumList() {
List<Integer> pageNumList = new ArrayList<Integer>();
List<WebElement> aElementList = driver.findElement(By.className("page")).findElements(By.tagName("a"));
for (WebElement aElement : aElementList) {
String pageNum = aElement.getText();
if (isNumber(pageNum) == true) {// 调用判断pageNum是不是数字这个方法
// 将string类型的pageNum转换为integer类型的添加到pageNumList这个集合中
pageNumList.add(Integer.valueOf(pageNum).intValue());
}
}
return pageNumList;//将获取到的页码返回出去
}

// 判断pageNum是不是数字
public boolean isNumber(String pageNum) {
Pattern pattern = Pattern.compile("[0-9]*");// 设置正则
Matcher isNum = pattern.matcher(pageNum);// 把pageNum和正则表达式进行匹配
if (isNum.matches()) {
return true;
}
return false;
}

原文地址:https://www.cnblogs.com/wangffeng293/p/12507411.html