如何使用C#从Selenium中的元素中获取元素

How to get elements from element in Selenium using C#

如何从元素中 select elementS。例如,我有下一个元素 div 块,并希望从这个 div 块中 select 块所有类型等于 radio:

的元素
 private static readonly By divBlock =By.XPath("//*[@contains(@id, 'qst_8220_qst_8235')]");

 private static readonly By elementType = By.XPath(".//*[@type='radio']");

此代码对我不起作用:

foreach (var elem in WebDriver.FindElement(divBlock).FindElements(elementType))
        {
            elem.Click();
        }

Error: Object reference not set to an instance of an object.

试试这个方法:

IWebDriver Driver = new (select some driver);

var divBlock = Driver.FindElement(By.Xpath("//*[@contains(@id, 'qst_8220_qst_8235')]"));

var elementType = Driver.FindElements(By.XPath(".//*[@type='radio']"));

foreach (var elem in elementType.Count)
{
elem.Click();
}

IWebElement 有方法 findelements。所以你可以这样试试

private static readonly By divBlock =By.XPath("//*[@contains(@id, 'qst_8220_qst_8235')]");

private static readonly By elementType = By.XPath(".//*[@type='radio']");

IWebElement Block = Driver.FindElement(divBlock);

List<IWebElement> elementTypes = Block.FindElements(elementType);

Console.WriteLine(elementTypes.count);

foreach (var elem in elementTypes)
{
    elem.Click();
}