首页 > 解决方案 > 引起:org.openqa.selenium.InvalidSelectorException:

问题描述

我是 Selenium 自动化测试的新手遇到 Selenium 错误

当我每次遇到错误“org.openqa.selenium.TimeoutException:预期条件失败:等待 By.xpath 定位的元素的可见性”时尝试运行以下代码时,我不确定 xpate 会是什么,请有人帮忙我为登录应用程序创建了自动化测试用例。

爪哇:

@Test
    public void enterApplicationCerdentials(String userName, String password) {

 WebDriverWait wait = new WebDriverWait(driver, 50);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id='UserID' and name='UserID'])"))).sendKeys(userName);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password"))).sendKeys("CSRWHKXESB");
 captureScreen();
 }

HTML:

<frameset rows="*, 1">

<frame src="Script/Login.asp?">
#document
<!--Function return the password for the user who logged in through Referral URL. 
          For TAFE user password is not matching as per database value as their URL is dynamic. ENHC0014091
          This function splits the URL of that particular user (8527066229)   only  . -->

<html><head>



<script language="JavaScript">
//<!--
function OnLoad()
{
  setTimeout("CheckFrame()", 4000);
}

function CheckFrame()
{
  with (parent)
  {
    if ((length==0 && document.frmCheck==null) || 
        (length>0 && frames[1].document.frmCheck==null))
    {
      var PathName = window.location.pathname;
      PathName = PathName.substr(0, PathName.substr(1).indexOf("/") + 1);
      location.href = PathName;
    }
  }
}
//-->
</script></head>



<body onload="OnLoad()" topmargin="0" leftmargin="0" bgcolor="#ffffff" text="#000000" link="#000000" vlink="#000000" alink="#000000">

<div id="login">
<img border="0" src= vspace="10" style="display: block;">
<div class="tintedBox" id="InfoStoreBox">
<h1>  <a class="boldLink" href="https://infostore.saiglobal.com" target="_parent"><u>InfoStore</u></a> ?</h1>
<p></p>
<p><a class="boldLink" href="https://infostore.saiglobal.com" target="_parent"></a> .</p>
<p>Not only a shop, <a class="boldLink" href="https://infostore.saiglobal.com" target="_parent"></a> </p>
<p><a href="https://infostore.saiglobal.com" target="_parent"></a></p>
</div>

<div class="tintedBox" id="loginBox">
<h1></h1>

<form name="form" action="Login.asp?" method="post">
  <input type="hidden" name="Autologout" value="false">
  <input type="hidden" name="Division" value="">
  <span class="error"></span>
  <table>
      <tbody><tr>
          <td>User ID</td>
          <td><input type="text" size="30" id="UserID" name="UserID" value=""></td>
      </tr>
      <tr>
          <td>Password</td>
          <td><input type="password" size="30" id="Password" name="Password" value=""></td>
      </tr>
          <tr>
          <td>Last Name/Location</td>
          <td><input type="text" size="30" id="UserName" name="UserName" value=""></td>
      </tr>
  </tbody></table>
  <br>
  <font color="#d12b2c"><nobr>Your Last Name and Location are now mandatory to access the platform, simply</nobr><br>enter the details in field (e.g. Smith/Perth)</font>
  <br><br>
  <div>
    <input type="checkbox" id="SaveLogin" name="SaveLogin" value="SaveLogin"><label for="SaveLogin" id="save">Save my login so you can remember me on my next visit.</label>
  </div>
  <div align="center" style="padding-top:20px">
    <input class="button" type="submit" name="Submit" value="Submit">
    <input class="button" type="reset" name="Clear" value="Clear">
    <input class="button" type="submit" name="Recognize" value="Remember me?">
  </div>
  <div style="padding-top:20px">
    <nobr>Lost password? Contact your internal Administrator or <a class="boldLink" href="mailto:sales@saiglobal.com?subject=Lost SOL password">our Customer Service</a></nobr>
  </div>
</form>
</div>





</div>
<div id="footer" onmouseover="ShowTime()">©2014 SAI Global</div>
<script>
  function ShowTime()
  {
    var spTime = document.getElementById("footer");
    spTime.innerHTML = "©2014 SAI Global - 20190426 12:25:33.292: 172.20.33.12, 203.27.21.6, 59596377";
  }
</script>


</body></html>

错误:

(resources/features/DataDrivenLogin.feature:7) 原因:org.openqa.selenium.InvalidSelectorException:无效选择器:无法使用 xpath 表达式定位元素 //frameset/frame/html/body/div([@class= 'tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id='UserID' and name='UserID']) 因为以下错误: SyntaxError: Failed to execute 'evaluate'在'文档'上:字符串'//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id=' UserID' and name='UserID'])' 不是有效的 XPath 表达式。(会话信息:chrome=73.0.3683.103)(驱动程序信息:chromedriver=2.46.628402(536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),平台=Windows NT 6.3.9600 x86_64)(警告: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html 构建信息:版本:'3.141.59',修订:'e82be7d358',时间:'2018-11-14T08:25:48' 系统信息:主机:'AP01154W8N',ip:'192.168.56.1',os.name : 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_191' 驱动信息: org.openqa.selenium.chrome.ChromeDriver Capabilities {acceptInsecureCerts: false, acceptSslCerts : false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628402 (536cd7adbad73a..., userDataDir: C:\Users\sinham0\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled:false,goog:chromeOptions:{debuggerAddress:localhost:65139},handlesAlerts:true,hasTouchScreen:false,javascriptEnabled:true,locationContextEnabled:true,mobileEmulationEnabled:false,nativeEvents:true,networkConnectionEnabled:false,pageLoadStrategy:正常,平台:XP,platformName:XP,代理:Proxy(),rotatable:false,setWindowRect:true,strictFileInteractability:false,takesHeapSnapshot:true,takeScreenshot:true,超时:{隐式:0,pageLoad:300000,脚本:30000},unexpectedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:73.0.3683.103,webStorageEnabled:true} 会话 ID:869efd2308887ee98e8d561566b5a606 ***元素信息:{Using=xpath,值=//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id='UserID' and name='UserID '])} 在 sun.reflect.GeneratedConstructorAccessor10.newInstance(Unknown Source)假,pageLoadStrategy:正常,平台:XP,平台名称:XP,代理:Proxy(),可旋转:假,setWindowRect:真,strictFileInteractability:假,takesHeapSnapshot:真,takeScreenshot:真,超时:{隐式:0,pageLoad:300000 , script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 73.0.3683.103, webStorageEnabled: true} Session ID: 869efd2308887ee98e8d561566b5a606 *** Element info: {Using=xpath, value=//frameset/frame/html/body /div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id='UserID' and name='UserID'])} 在 sun.reflect.GeneratedConstructorAccessor10 .newInstance(未知来源)假,pageLoadStrategy:正常,平台:XP,平台名称:XP,代理:Proxy(),可旋转:假,setWindowRect:真,strictFileInteractability:假,takesHeapSnapshot:真,takeScreenshot:真,超时:{隐式:0,pageLoad:300000 ,脚本:30000},unexpectedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:73.0.3683.103,webStorageEnabled:true} 会话 ID:869efd2308887ee98e8d561566b5a606 *** 元素信息:{Using=xpath, value=//frameset/frame/html/body /div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input[@id='UserID' and name='UserID'])} 在 sun.reflect.GeneratedConstructorAccessor10 .newInstance(未知来源)strictFileInteractability:false,takesHeapSnapshot:true,takeScreenshot:true,超时:{implicit:0,pageLoad:300000,脚本:30000},unexpectedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:73.0.3683.103,webStorageEnabled:true} 会话 ID:869efd2308887ee98e8d56156 *** 元素信息:{Using=xpath, value=//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input [@id='UserID' and name='UserID'])} at sun.reflect.GeneratedConstructorAccessor10.newInstance(Unknown Source)strictFileInteractability:false,takesHeapSnapshot:true,takeScreenshot:true,超时:{implicit:0,pageLoad:300000,脚本:30000},unexpectedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:73.0.3683.103,webStorageEnabled:true} 会话 ID:869efd2308887ee98e8d56156 *** 元素信息:{Using=xpath, value=//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/input [@id='UserID' and name='UserID'])} at sun.reflect.GeneratedConstructorAccessor10.newInstance(Unknown Source)869efd2308887ee98e8d561566b5a606 *** 元素信息:{Using=xpath, value=//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/ sun.reflect.GeneratedConstructorAccessor10.newInstance 处的输入[@id='UserID' and name='UserID'])}(未知来源)869efd2308887ee98e8d561566b5a606 *** 元素信息:{Using=xpath, value=//frameset/frame/html/body/div([@class='tintedBox' and @id='loginBox']/table/tbody/tr/td/ sun.reflect.GeneratedConstructorAccessor10.newInstance 处的输入[@id='UserID' and name='UserID'])}(未知来源)

标签: seleniumautomation

解决方案


你得到的原因TimeoutException是你找到的元素在一个框架中,你必须切换到那个框架。否则,webdriver 找不到元素。

frame首先,为标签找到合适的选择器。根据您提供的 HTML,我正在构建定位器。

XPath:

WebElement loginFrame = driver.findElement(By.xpath("//frameset/frame[@src='Script/Login.asp?']"));

CSS 选择器:

WebElement loginFrame = driver.findElement(By.cssSelector("frameset > frame[src='frame_c.htm']"));

尝试这个:



@Test
public void enterApplicationCerdentials(String userName, String password) {
WebDriverWait wait = new WebDriverWait(driver, 50);
By frameLocator =  By.xpath("//frameset/frame[@src='Script/Login.asp?']");

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//frameset/frame[@src='Script/Login.asp?']")));
driver.switchTo().frame(driver.findElement(frameLocator));

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName"))).sendKeys("UserName");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password"))).sendKeys("Password");
captureScreen();
}

推荐阅读