如何打印随机选择的索引值?

时间:2018-12-26 09:26:00

标签: selenium-webdriver

我无法打印我从下拉列表中随机选择的值,例如,如果我选择了索引4,而索引4的值为“ ABC”,那么它将打印4,而不是ABC。您能帮我解决这个问题吗?

我尝试过将索引转换为字符串,但是没有用

public class SC {

    public static void main(String[] args) throws Exception {

System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dell\\Downloads\\chromedriver_win32 (2)\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://website name");
        JavascriptExecutor js = (JavascriptExecutor) driver;


FileInputStream fis=new FileInputStream("C:\\Excel_data\\Testdata.xlsx");
               Workbook wb=WorkbookFactory.create(fis);
    Sheet sh=wb.getSheet("Sheet1");

        for(int i=0; i<=3; i++) 
            {
            Actions act = new Actions(driver);

        act.moveToElement(driver.findElement(By.xpath("//*[@id='navbar-main']/div/div[2]/ul/li[3]/a"))).perform();
                driver.manage().timeouts().implicitlyWait(1,TimeUnit.MINUTES);
                            driver.findElement(By.xpath("//*[@id=\"navbar-main\"]/div/div[2]/ul/li[3]/ul/li[3]/div/ul/li[2]/a")).click();       //*[@id="navbar-main"]/div/div[2]/ul/li[3]/ul/li[3]/div/ul/li[2]/a

WebElement list = driver.findElement(By.xpath("//*[@id=\"categoryDropDown\"]"));
        Random random = new Random();
        int index = random.nextInt(4)+1;
        Select listfin = new Select(list);
        listfin.selectByIndex(index);
        Thread.sleep(2000); 

WebElement itemsInDropdown1 = driver.findElement(By.xpath("//*[@id=\"policyTermDropDown\"]"));
           Random random1 = new Random();
           int index1 = random.nextInt(4)+1;
           Select list1 = new Select(itemsInDropdown1);
           list1.selectByIndex(index1);
           Thread.sleep(2000);

        js.executeScript("window.scrollBy(0,-500)"); 
        Thread.sleep(1500);
        String a= driver.findElement(By.xpath("//*[@id=\'totalCount\']")).getText();
            System.out.println(a +" "+"Scheme Found");


    sh.getRow(0).createCell(i).setCellValue(a + " "+"Scheme found");

FileOutputStream fos=new FileOutputStream("C:\\Excel_data\\Testdata.xlsx");
                        wb.write(fos);
                fos.close();
                }
            driver.close();

                }
            }

1 个答案:

答案 0 :(得分:0)

有疑问的是,只有打印语句是

String a= driver.findElement(By.xpath("//*[@id=\'totalCount\']")).getText();
        System.out.println(a +" "+"Scheme Found");

因此将打印id=totalCount中可用的文本。

如果要在下拉菜单中打印所选选项,则

 WebElement option = list1.getFirstSelectedOption();
    System.out.println(option.getAttribute("value"));

这将为list1下拉列表打印选定的选项