簡體   English   中英

如何從列表中選擇元素,單擊它,返回列表,然后使用Selenium Webdriver選擇下一個元素

[英]How to select element from the list, click on it, go back to the list and select next element using selenium webdriver

我正在嘗試編寫一個小型應用程序(機器人),該應用程序將使用網絡驅動程序登錄網站,在搜索字段中搜索一些數據,然后從列表中選擇每個元素,方法是單擊其中的一個,返回列表,然后選擇具有相同類名但父級不同的下一個元素。 我想我知道如何獲取具有相同類名的所有元素:

List<WebElement> incognito_user = driver.findElements(By.xpath("//*[@id='results']/li[2]/div/h3/a"))

但是我需要一些for循環的幫助,這些循環會為所有循環編制索引,並轉到下一頁。

我已經以不同的方式解決了這個問題:

    boolean inLoop = true;
    int maxPages = 2;

    while(inLoop && (maxPages-- > 0)) {
        List<WebElement> incognito_user = driver.findElements(By.xpath("xpath"));
        String openInNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
        for (WebElement element : incognito_user) {
            element.sendKeys(openInNewTab);
            driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
            waitSecs(randomNumber(5, 10));
            driver.switchTo().window(new ArrayList<String>(driver.getWindowHandles()).get(1));
            driver.close();
            driver.switchTo().window(new ArrayList<String>(driver.getWindowHandles()).get(0));
            waitSecs(randomNumber(5,10));
        }

        List<WebElement> nextElements = driver.findElements(By.xpath("xpath"));
        if (nextElements.size() > 0) {
            nextElements.get(0).click();
            waitSecs(randomNumber(5,10));
        }
        else {
            inLoop = false;
        }
    }

謝謝您的努力。 親切的問候

如果您需要處理元素列表,請為硒創建一個包裝器

click()

public String clickButton(String parentClassIdentifier,String childClassIdentifier ,String index) throws IOException{

                WebElement parentButtonList = (WebElement)driver.findElementByXPath((parentClassIdentifier));
                List<WebElement> childButtonList = parentButtonList.findElementsByXPath((childClassIdentifier));
                int button_index = Integer.parseInt(prop.getProperty(index));   // conversion from String to Int
                childButtonList.get(button_index).click();
                Application_Log.info("Clicked on button :- " ,childClassIdentifier    +index );
                return "pass";

}

只需在代碼中傳遞標識符和列表索引即可使用clickButton()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM