在C#中使用Selenium通过部分id查找元素

Mic*_*ell 14 c# regex selenium

我试图找到一个动态生成id的元素.字符串的最后一部分是常量("ReportViewer_fixedTable"),所以我可以使用它来定位元素.我试图在XPath中使用正则表达式:

targetElement = driver.FindElement(
    By.XPath("//table[regx:match(@id, "ReportViewer_fixedTable")]"));
Run Code Online (Sandbox Code Playgroud)

并通过CssSelector定位:

targetElement = driver.FindElement(
    By.CssSelector("table[id$='ReportViewer_fixedTable']"));
Run Code Online (Sandbox Code Playgroud)

两者都不起作用.任何建议,将不胜感激.

Gre*_*reg 37

那是因为css选择器需要修改你几乎就在那里......

driver.FindElement(By.CssSelector("table[id*='ReportViewer_fixedTable']"))`
Run Code Online (Sandbox Code Playgroud)

来自https://saucelabs.com/blog/selenium-tips-css-selectors-in-selenium-demystified:

css=a[id^='id_prefix_']
Run Code Online (Sandbox Code Playgroud)

id带有以文本开头的链接id_prefix_.

css=a[id$='_id_sufix']
Run Code Online (Sandbox Code Playgroud)

id带有文本结尾的链接_id_sufix.

css=a[id*='id_pattern']
Run Code Online (Sandbox Code Playgroud)

id包含文本的链接id_pattern.

您使用的是后缀,我假设它不是您应该使用的部分链接文本标识符(除非我看到您的html,这意味着下次尝试显示您的HTML).*=但在任何情况下都是可靠的.