Selenium C#Webdriver FindElements(By.LinkText)RegEx?

是否可以通过使用类似A-ZNN:NN:NN:NN的模式搜索其文本来查找网页上的链接,其中N是单个数字(0-9)。

我在PHP中使用了Regex将文本转换为链接,所以我想知道是否可以在Selenium中使用这种filter和C#来查找按照某种格式看起来相同的链接。

我试过了:

 driver.FindElements(By.LinkText("[AZ][0-9]{2}):([0-9]{2}):([0-9]{2}):([0-9]{2}")).ToList(); 

但这没效果。 任何建议?

总之,不, FindElement()策略都不支持使用正则表达式来查找元素。 最简单的方法是使用FindElements()查找页面上的所有链接,并将其.Text属性与正则表达式匹配。

请注意,如果单击链接导航到同一浏览器窗口中的新页面(即,单击链接时未打开新的浏览器窗口),则需要捕获所有链接的确切文本我想点击以备日后使用。 我之所以提到这一点,是因为如果您尝试保留对初始FindElements()调用期间找到的元素的引用,则在单击第一个之后它们将过时。 如果这是您的方案,代码可能如下所示:

 // WARNING: Untested code written from memory. // Not guaranteed to be exactly correct. List matchingLinks = new List(); // Assume "driver" is a valid IWebDriver. ReadOnlyCollection links = driver.FindElements(By.TagName("a")); // You could probably use LINQ to simplify this, but here is // the foreach solution foreach(IWebElement link in links) { string text = link.Text; if (Regex.IsMatch("your Regex here", text)) { matchingLinks.Add(text); } } foreach(string linkText in matchingLinks) { IWebElement element = driver.FindElement(By.LinkText(linkText)); element.Click(); // do stuff on the page navigated to driver.Navigate().Back(); } 

不要使用正则表达式来解析Html。

使用htmlagilitypack

您可以按照以下步骤操作:

步骤1使用HTML PARSER从特定网页中提取所有链接并将其存储到列表中。

 HtmlWeb hw = new HtmlWeb(); HtmlDocument doc = hw.Load(/* url */); foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href]")) { //collect all links here } 

步骤2使用此正则表达式匹配列表中的所有链接

 .*?[AZ]\d{2}:\d{2}:\d{2}:\d{2}.*? 

第3步,您将获得所需的链接。