简体   繁体   中英

C# How to select the exact matching nodes in selenium Page factory

I am facing the issue in following element,addition to that this element is placed inside the table

 [FindsBy(How = How.XPath, Using = "//button[contains(text(),'Cancel')]")]
    private IWebElement FilterCancelBtn { get; set; }

You can not use variables in FindsBy, this section is usually used for "static" and unique elements when searching the dom. Try to find it dynamically. You could get the table ID, the search for all elements whose text contain/equals your text. One solution could be the one below:

//Try to find your button by it's tag (if it's an anchor for example).
//If your table is unique, then search the table instead of dom, it's faster.
ReadOnlyCollection<IWebElement> buttons = table.FindElements(By.TagName("a")); 

//And then, with linq or foreach, go through each button to see if it matches your text.
IWebElement desiredButton = (from button in buttons
                             where button.Text.Equals("Your Button's Text")
                             select button).SingleOrDefault();

//LinQ will select your desired button by searching for it's text. 
//If it is not found, will return null.

And then just put everything above in a method or property. Eg:

public IWebElement GetButton()
{
    IWebElement table = driver.FindElement(By.Id("your table's id");
    string buttonText = "Your Button's Text";
    ReadOnlyCollection<IWebElement> buttons = table.FindElements(By.TagName("a")); 

    IWebElement desiredButton = (from button in buttons
                                 where button.Text.Equals(buttonText)
                                 select button).SingleOrDefault();
    return desiredButton;
}

If you want, you can replace SingleOrDefault() with Single() so you can get an exception if the button is not found (in case you are sure that it MUST be in the dom). But I suggest against it. It would be a better choice to just use Assert method and check that Assert.IsNotNull() and throw a message that is better to understand. Eg:

Assert.IsNotNull(desiredButton, "Button "+ buttonText +" was not found");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM