使用 Selenium 和 C# 通过部分 ID 查找元素。


我们可以使用 Selenium 和 C# 通过部分 ID 查找元素。这可以通过使用定位器的 **CSS** 和 **xpath** 来识别元素来实现。正则表达式用于查找部分匹配的元素。

让我们研究一下具有 gsc−i−id1 值的元素的 id 属性。

在 xpath 中,我们利用 contains() 函数进行部分匹配。因此,这里的 xpath 表达式将是 //*[contains(@id, 'id')]。这是因为子文本 id 在文本 gsc−i−id1 中。我们还可以借助 starts−with() 函数。因此,xpath 表达式变为 //*[starts−with(@id, 'gsc')],因为文本 gsc−i−id1 以子文本 gsc 开头。

在 CSS 中,我们利用 * 符号进行部分匹配。因此,这里的 CSS 表达式将是 input[id*='id']。这是因为子文本 id 在文本 gsc-i-id1 中。我们还可以借助 ^ 符号。因此,CSS 表达式变为 input[id^='gsc'],因为文本 gsc−i−id1 以子文本 gsc 开头。此外,我们可以使用 $ 符号。因此,xpath 表达式变为 input[id$='id1'],因为文本 gsc−i−id1 以子文本 id1 结尾。

为了实现,我们将使用 NUnit 框架。

示例

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String u =
      "https://tutorialspoint.com/about/about_careers.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         d.Navigate()
         .GoToUrl(u);
         // identify element with * in CSS
         IWebElement l
         = d.FindElement(By.CssSelector("input[id*='id']"));
         l.SendKeys("C#");
         //obtain input value
         Console.WriteLine(l.GetAttribute("value"));
         l.Clear();
         // identify element with ^ in CSS
         IWebElement m
         = d.FindElement(By.CssSelector("input[id^='gsc']"));
         m.SendKeys("NUnit");
         //obtain input value
         Console.WriteLine(m.GetAttribute("value"));
         m.Clear();
         // identify element with $ in CSS
         IWebElement n
         = d.FindElement(By.CssSelector("input[id$='id1']"));
         n.SendKeys("Selenium");
         //obtain input value
         Console.WriteLine(n.GetAttribute("value"));
         n.Clear();
         // identify element with contains in xpath
         IWebElement o = d.
         FindElement(By.XPath("//input[contains(@id,'id')]"));
         o.SendKeys("Java");
         //obtain input value
         Console.WriteLine(o.GetAttribute("value"));
         o.Clear();
         // identify element with starts-with() in xpath
         IWebElement p = d.
         FindElement(By.XPath("//input[starts−with(@id,'gsc')]"));
         p.SendKeys("Python");
         //obtain input value
         Console.WriteLine(p.GetAttribute("value"));
         p.Clear();
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}

输出

点击 **运行所有测试** -

点击 **打开此结果的其他输出** 链接 -

我们应该得到 **测试结果** 和 **标准输出**。

更新于: 2021年1月30日

1K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.