开发者

How to optimize this Selenium WebDriver code (Linq?)

I'm new to Selenium and C#.

I know this code is not optimal, can you advise ho开发者_C百科w I can write such things quicker and shorter?

Basically I am searching for a button, href of which contains "addNewProduct".

        var addButtons = _driver.FindElements(By.LinkText("Add"));
        IWebElement addNewProductButton = null;

        foreach (IWebElement button in addButtons) {
            if (button.GetAttribute("href").Contains("addNewProduct")){
                addNewProductButton = button;
                break;
            }
        }

        addNewProductButton.Click();


Make use of XPath or CSS Selector.

XPath

IWebElement btnAdd = _driver.FindElement(By.XPath("//a[contains(@href, 'addNewProduct')]"));

CSS Selector

IWebElement btnAdd = _driver.FindElement(By.CssSelector("a[href*='addNewProduct']"));

I recommend CSS Selector since they are faster and the syntax is more concise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜