使用 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.tw/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(); } } }
輸出
點選 **執行所有測試** -
點選 **開啟此結果的其他輸出** 連結 -
我們應該得到 **測試結果** 和 **標準輸出**。
廣告