Selenium测试代码By.xpath提示xpath方法未定义问题求解
报错问题解决方法
错误原因
- 导包错误:导入了非Selenium官方的
By类,没有导入org.openqa.selenium.By,导致找不到内置的xpath方法 - 依赖问题:项目缺少Selenium核心依赖,或者使用的Selenium版本和PhantomJS不兼容
解决步骤
- 修正导包
在代码顶部添加以下正确的导入语句,删除其他错误的By类导入:
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.Test;
- 核对依赖配置
PhantomJS仅支持Selenium 3.x版本,不要使用4.x及以上版本的Selenium。如果是Maven项目,在pom.xml中添加如下依赖:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency>
- 可选优化:替换更稳定的元素定位
谷歌搜索框的class属性是动态生成的,上线后可能失效,推荐用name属性定位:
driver.findElement(By.name("q")).sendKeys("Fresco Play"); driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
内容的提问来源于stack exchange,提问作者Sambit
相关产品推荐
相关产品推荐

