I am trying to locate an element with a dynamically generated id. The last part of the string is constant ("ReportViewer_fixedTable"), so I can use that to locate the element. I have tried to use regex in XPath:
targetElement = driver.FindElement(
By.XPath("//table[regx:match(@id, "ReportViewer_fixedTable")]"));
And locating by CssSelector:
targetElement = driver.FindElement(
By.CssSelector("table[id$='ReportViewer_fixedTable']"));
Neither works. Any suggestions would be appreciated.
We can locate elements by partial id match with Selenium webdriver. This can be achieved while we identify elements with the help of xpath or css locator. With the css and xpath expression, we use the regular expression to match id partially.
We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By. cssSelector. To identify the element with xpath, the expression should be //tagname[@id='value'].
We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.
Step 1: Type “css=input#Email” i.e. the locator value in the target box in the Selenium IDE and click on the Find button. Notice that the Email Text box would be highlighted. HTML tag – It is the tag which is used to denote the web element which we want to access. # – The hash sign is used to symbolize ID attribute.
That is because the css selector needs to be modified you were almost there...
driver.FindElement(By.CssSelector("table[id*='ReportViewer_fixedTable']"))`
From https://saucelabs.com/blog/selenium-tips-css-selectors-in-selenium-demystified:
css=a[id^='id_prefix_']
A link with an id
that starts with the text id_prefix_
.
css=a[id$='_id_sufix']
A link with an id
that ends with the text _id_sufix
.
css=a[id*='id_pattern']
A link with an id
that contains the text id_pattern
.
You were using a suffix which I'm assuming was not the partial link text identifier you were supposed to be using (unless I saw your html, which means try showing your html next time). *=
is reliable in any situation though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With