Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element by partial id with Selenium in C#

Tags:

c#

regex

selenium

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.

like image 641
Michael Howell Avatar asked Aug 14 '12 21:08

Michael Howell


People also ask

Can we find element by partial ID match in Selenium?

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.

How do I select an element by ID in Selenium?

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'].

How can we locate an element by only partially matching the value of its attributes in xpath?

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.

How do I use css to locate an element by ID?

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.


1 Answers

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.

like image 176
Greg Avatar answered Sep 30 '22 21:09

Greg