Visual Studio 2019中Selenium C#无法使用FindElement(By)的替代方案
解决方案
你的问题核心是缺少必要命名空间,同时混淆了Java与C#版Selenium的语法差异,以下是具体解决方法:
1. 添加关键命名空间
By类属于OpenQA.Selenium命名空间,你的代码未引入该命名空间,导致编译器无法识别By。需在using块中添加:
using OpenQA.Selenium;
2. 修正C#版Selenium语法
C#版Selenium采用PascalCase命名规范,与Java的camelCase不同:
- Java写法:
driver.findElement(By.cssSelector("selector")) - C#写法:
driver.FindElement(By.CssSelector("selector"))
修改后的完整代码示例
using OpenQA.Selenium; // 新增的必需命名空间 using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Interactions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WebDriverTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://www.marketinginternetdirectory.com/submit.php"); // 示例:通过CSS选择器定位标题输入框,请替换为实际页面的选择器 var title_field = driver.FindElement(By.CssSelector("input[name='title']")); // 可选:向输入框填充内容 title_field.SendKeys("测试标题内容"); } } }
额外优化:处理元素加载延迟
若页面加载缓慢导致元素定位失败,建议使用显式等待确保元素加载完成:
// 最长等待10秒,直到元素出现 var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); var title_field = wait.Until(driver => driver.FindElement(By.CssSelector("input[name='title']")));
常用元素定位方式
除CssSelector外,还可根据元素属性选择以下定位方式:
By.Id("element-id"):通过元素ID定位(优先级最高)By.Name("element-name"):通过元素name属性定位By.XPath("//input[@name='title']"):通过XPath表达式定位By.ClassName("element-class"):通过元素class属性定位
内容的提问来源于stack exchange,提问作者Ronen Amir
相关产品推荐
相关产品推荐

