java - 获取正确的搜索结果页码 - Selenium Java

标签 java selenium while-loop

我正在尝试获取西雅图的正确页码,即 7,然后单击从 1 到 7 的每个页面。我有 2 个问题,请参阅下面带星号 ** 的部分:

1) 我不知道如何编写 xpath 以便得到 7 而不是 11

2)while循环是无限循环

public class Job {

    public static WebDriver driver;

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Shahriar\\Downloads\\chromedriver_win32\\chromedriver.exe");
        driver= new ChromeDriver();
        driver.get("https://web.expeditors.com/careers/#/listTop");
        driver.manage().window().maximize();

        //Disable the cookie notification at bottom
        driver.findElement(By.xpath("//a[@id='hs-eu-decline-button']")).click();

        // Find more cities and scroll down
        driver.findElement(By.xpath("//a[@id='moreCity']")).click();
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("window.scrollBy(0,5500)", "");

        //Locate US-Seattle and click and verify
        driver.findElement(By.xpath("//label[@class='ng-binding']//input[@id='us~Seattle']")).click();
        String state=driver.findElement(By.xpath("//a[contains(text(),'United States - Seattle')]")).getText();
        Assert.assertEquals(state, "United States - Seattle");

        **//Number of search pages found should be 7
         List<WebElement> resultPages=driver.findElements(By.xpath("//a[@href='#listTop']"));
        Assert.assertEquals(7, resultPages.size());**

        **//Go to each page by clicking on page number at bottom
        int count=0;
        WebElement next_button=driver.findElement(By.xpath("//a[@ng-click='setCurrent(pagination.current + 1)']"));
        while (resultPages.size()!=0){
            next_button.click();
            count++;
            System.out.println("Current page is "+ count);                  
        }**
        //driver.close();
    }
}

我需要一些帮助。预先感谢您的宝贵时间。

最佳答案

这是您需要的逻辑。

//Number of search pages found should be 7
     List<WebElement> resultPages=driver.findElements(By.xpath("//a[@href='#listTop' and @ng-click='setCurrent(pageNumber)']"));
    Assert.assertEquals(7, resultPages.size());

    for (int i = 1; i <= resultPages.size(); i++) {
        driver.findElement(By.xpath("(//a[@href='#listTop' and @ng-click='setCurrent(pageNumber)'])[" + i +"]")).click();
        System.out.println(driver.findElement(By.xpath("(//a[@href='#listTop' and @ng-click='setCurrent(pageNumber)'])[" + i +"]")).getText());
    }

关于java - 获取正确的搜索结果页码 - Selenium Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911353/

相关文章:

java - 无法恢复嵌套 fragment 状态

python - 单击 Selenium 中的链接后让 Firefox 等待新页面加载?

swift - 缓慢的 while 循环。 swift

c - 下面的代码在 C 中做了什么?

java - Spring 多部分文件最大大小

java - 如何以编程方式限制 Eclipse (Message)Console 的缓冲区大小?

java - Android 中的自动登录

java - Selenium:如何使用selenium打开chrome扩展/或登录chrome扩展

java - 正则表达式未从所有字段中获取正确的值

c - 无法用 for 循环替代的 while 循环示例