简体   繁体   中英

How to use wildcards in CssSelector when finding an element through Selenium?

I have an issue where the CssSelector I am using has a GUID in it that changes every time and therefore the tests will only ever pass once. Is there a wildcard I can use in the CssSelector that will help me get round this? Consider the following code...

IWebElement PersonalPhone = Driver.driver.FindElement(By.CssSelector("# Grid365e0689-dccb-695f-97af-dc29187d4e1d-id-cell-0-7 > a"));
PersonalPhone.Click();

I would like the above code to locate the element via the CssSelector using a wildcard so that I can remove the GUID part of the selector and only find the element based on the last part 'id-cell-0-7' and then click on the element.

I am using Selenium WebDriver(Chrome) written in C#

Any ideas?

You can use partial id with contains *=

IWebElement PersonalPhone = Driver.driver.FindElement(By.CssSelector("[id*='id-cell-0-7'] > a"));

Or end with $=

IWebElement PersonalPhone = Driver.driver.FindElement(By.CssSelector("[id$='id-cell-0-7'] > a"));

The value of the id attribute looks dynamic to me so as an alternative you can use the following :

IWebElement PersonalPhone = Driver.driver.FindElement(By.CssSelector("[id^='Grid'][id*='-id-cell-'] > a"));
PersonalPhone.Click();

Optimizing the lines of code in a single line:

Driver.driver.FindElement(By.CssSelector("[id^='Grid'][id*='-id-cell-'] > a")).Click();

Explanation

The id attribute:

  • Always start with Grid followed by the dynamic value, so you can use ^ to indicate starts-with
  • Always contain -id-cell- at the rear end, so you can use * to indicate contains

However, as the desired element is a dynamic element so to invoke click() on the element you may have to induce WebDriverWait for the ElementToBeClickable() and you can use either of the following Locator Strategies :

  • CssSelector :

     new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("[id^='Grid'][id*='-id-cell-'] > a"))).Click();
  • XPath :

     new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*[starts-with(@id, 'Grid') and contains(@id, '-id-cell-')]/a"))).Click();

I am sorry to give you this news, but xpath 1.0 its still used in most drivers... quite:

As other answers have noted, XPath 1.0 does not support regular expressions.

Suggested way is to use the parent elements to locate the element you wish to click.

or.. if the grid-xxx--xxx-- id keyword is constant you can do something like

Xpath: //*[starts-with(@id, 'Grid')]/a - id starts with Grid

CSS: input[id^='Grid'] > a - id starts with Grid

Change the input to the actual web element.

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