using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
class Program
{
static void Main(string[] args)
{
// 创建 ChromeDriver 实例
IWebDriver driver = new ChromeDriver();
// 访问页面
driver.Navigate().GoToUrl("https://www.example.com");
// 使用 CSS 选择器查找元素
IWebElement elementByCssSelector = driver.FindElement(By.CssSelector("div#main-content"));
// 使用 class 名称查找元素
IWebElement elementByClassName = driver.FindElement(By.ClassName("example-class"));
// 打印元素文本内容
Console.WriteLine(elementByCssSelector.Text);
Console.WriteLine(elementByClassName.Text);
// 关闭浏览器
driver.Quit();
}
}
在这个示例中,FindElement
方法使用 By.CssSelector
来查找 id 为 main-content
的 div
元素,By.ClassName
方法使用 class
名称为example-class
的元素。找到元素后,可以使用元素的 Text
属性来获取元素的文本内容。
需要注意的是,C# 的 Selenium API
与 Python 的 Selenium API
略有不同,需要引入不同的命名空间并使用不同的方法名。但是,它们的基本思路和用法是一致的。