无法使用ID和CSS选择器方法定位元素

时间:2018-12-03 20:12:27

标签: selenium-webdriver

// //美国

copy selector = #ddlCountries
Select drpCountries = new Select(driver.findElement(By.id("ddlCountries")));
drpCountries.selectByValue("999");

我一直收到此错误,没有这样的元素:无法找到元素:{"method":"id","selector":"ddlCountries"}

1 个答案:

答案 0 :(得分:0)

使用SelectOptionInList(“ ddlCountries”,“ 999”);

public IWebDriver SelectOptionInList(string elementID, string optionValue)
    {
        SelectElement ElementSelect = new SelectElement(driver.FindElement(By.Id(elementID)));
        IList<IWebElement> ElementList = ElementSelect.Options;
        int ElementCount = ElementList.Count;

        for (int i = 0; i < ElementCount; i++)
        {
            string elementText = ElementList.ElementAt(i).Text;
            if (elementText.Equals(optionValue))
            {
                ElementList.ElementAt(i).Click();
                Console.WriteLine("Option " + optionValue + "Clicked");
                return driver;
            } 
            else if(elementText.Contains(optionValue))
            { 
                ElementList.ElementAt(i).Click();
                Console.WriteLine("Option " + optionValue + "Clicked");
                return driver;
            }
            else
            {
                Console.WriteLine("Option " + optionValue + " Not Found Under Element with ID: " + elementID);
            }
        }
        return driver;
    }