开发者

How to optimize this Selenium WebDriver code (Linq?)

开发者 https://www.devze.com 2023-04-12 03:07 出处:网络
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?

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

精彩评论

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