Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

regex - Finding an element by partial id with Selenium in C#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...