Reputation: 3
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?
Upvotes: 0
Views: 8268
Reputation: 193388
The value of the id
attribute looks dynamic to me so as an alternative you can use the following css-selectors:
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();
The id
attribute:
Grid
followed by the dynamic value, so you can use ^
to indicate starts-with-id-cell-
at the rear end, so you can use *
to indicate containsHowever, 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();
Upvotes: 1
Reputation: 2814
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.
Upvotes: 0
Reputation: 51009
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"));
Upvotes: 3