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

C# 在C中使用Selenium通过部分id查找元素#,c#,regex,selenium,C#,Regex,Selenium,我试图定位一个具有动态生成id的元素。字符串的最后一部分是常量(“ReportViewer_fixedTable”),因此我可以使用它来定位元素。我尝试在XPath中使用正则表达式: targetElement = driver.FindElement( By.XPath("//table[regx:match(@id, "ReportViewer_fixedTable")]")); 并通过CSS选择器进行定位: targetElement = driver.FindElement(

我试图定位一个具有动态生成id的元素。字符串的最后一部分是常量(“ReportViewer_fixedTable”),因此我可以使用它来定位元素。我尝试在XPath中使用正则表达式:

targetElement = driver.FindElement(
    By.XPath("//table[regx:match(@id, "ReportViewer_fixedTable")]"));
并通过CSS选择器进行定位:

targetElement = driver.FindElement(
    By.CssSelector("table[id$='ReportViewer_fixedTable']"));

两者都不起作用。如果您有任何建议,我们将不胜感激。

这是因为css选择器需要修改,您几乎就在那里了

driver.FindElement(By.CssSelector("table[id*='ReportViewer_fixedTable']"))`
发件人:

带有
id
的链接,以文本
id\u前缀
开头

css=a[id$='_id_sufix']
带有
id
的链接,以文本
\u id\u sufix
结尾

css=a[id*='id_pattern']
带有
id
的链接,其中包含文本
id\u模式

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

尝试使用

targetElement = driver.FindElement(By.XPath("//table[contains(@id, "ReportViewer_fixedTable")]"));

注意:这将检查id包含的所有元素(不仅以“ReportViewer\u fixedTable”结尾)。我将尝试找到一个更准确地回答您问题的正则表达式选项。

无论XPath版本如何,此解决方案都将有效。首先,在公共助手类中的某个位置创建一个方法

 public static string GetXpathStringForIdEndsWith(string endStringOfControlId)
    {
        return "//*[substring(@id, string-length(@id)- string-length(\"" + endStringOfControlId + "\") + 1 )=\"" + endStringOfControlId + "\"]";
    }
在我的情况下,以下是我的产品的不同版本中的控件ID::

v1.0::ContentPlaceholder默认\u MasterPlaceholder\u HomeLoggedOut\u 7\u hylHomeLoginCreateUser

v2.0::ContentPlaceholder默认\u MasterPlaceholder\u HomeLoggedOut\u 8\u hylHomeLoginCreateUser

然后,您可以调用上述方法来查找具有静态结束字符串的控件

By.XPath(Common.GetXpathStringForIdEndsWith("<End String of the Control Id>"))
总体逻辑是,您可以使用以下XPath表达式查找以特定字符串结尾的控件:

//*[substring(@id, string-length(@id)- string-length("<EndString>") + 1 )="<EndString>"]
/*[子字符串(@id,字符串长度(@id)-字符串长度(“”+1)=“”]

是的,一种肮脏的方式是//表[substring(@id,string length(@id)-22)='ReportViewer\u fixedTable']如何应用它对CSS类名进行部分匹配?我试图寻找具有类“custom label”或“countable custom label”的标签元素
By.CssSelector(“label[class$=custom label”)
似乎不起作用。我可以使用By.ClassName两次并合并结果,但仍然想知道如何使用CssSelector实现这一点。
By.XPath(Common.GetXpathStringForIdEndsWith("hylHomeLoginCreateUser"))
//*[substring(@id, string-length(@id)- string-length("<EndString>") + 1 )="<EndString>"]