如何解决正在获取org.openqa.selenium.NoSuchElementException:无此类元素:无法找到元素:{“ method”:“ xpath”,“ selector”:错误
我正在做自动化测试,并且是该领域的新手。我收到如下错误:
“ org.openqa.selenium.NoSuchElementException:无此类元素:无法 找到元素:{“ method”:“ xpath”,“ selector”:“
如果条件失败。 else if
和else
部分没有得到执行。
下面是对象类:
公共类createNewItemObjects扩展了BaseClass {
CommonActions commonActions = new CommonActions();
ReadAndWriteProperties readwriteprop = new ReadAndWriteProperties();
int totalItems = commonActions.getExcelRowNumbers(readwriteprop.getCompletePropertyCreationExcelPath(),readwriteprop.getItemsMenusTextDataSheetName());
static int i = 0;
//Constructor to initialize all web elements located by @FindBy annotation.
public createNewItemObjects(){
PageFactory.initElements(driver,this);
}
//'New Item' button
@FindBy(xpath = "//input[@name='new00N1U000006qwz9']")
public WebElement newItemBtn;
//'Item Record Type' DDB
@FindBy(xpath = "//select[@id='p3']")
WebElement itemRecordTypeDDB;
//'Continue' button
@FindBy(xpath = "//input[@value='Continue']")
WebElement continueBtn;
//'Item Name' text box
@FindBy(xpath = "//input[@name='Name']")
WebElement itemNameTxtBox;
//'Revenue Classification' Lookup button
@FindBy(xpath = "//img[@alt='Revenue Classification Lookup (New Window)']")
WebElement revenueClassificationLookupBtn;
//'Search Frame' on Lookup window
@FindBy(xpath = "//frame[@name='searchFrame']")
WebElement searchFrameName;
//'Revenue Classification' search box
@FindBy(xpath = "//div[@class='pBody']//input[@id='lksrch']")
WebElement revenueClassificationsSearchBox;
//'Go' button
@FindBy(xpath = "//input[@title='Go!']")
WebElement goBtn;
//'Result Frame' on Lookup window
@FindBy(xpath = "//frame[@name='resultsFrame']")
WebElement resultFrame;
//Revenue Classification 'Food'
@FindBy(linkText = "Food")
WebElement revenueClassificationNameFoodLinkTxt;
//Revenue Classification 'Beverage'
@FindBy(linkText = "Beverage")
WebElement revenueClassificationNameBeverageLinkTxt;
//'Quantity Calculation' DDB
@FindBy(xpath = "//select[@name='00N1U000006qwzC']")
WebElement quantityCalculationDDB;
//'Save' button
@FindBy(xpath = "//td[@id='bottomButtonRow']//input[@name='save']")
WebElement saveItemBtn;
//'Save and New' button
@FindBy(xpath = "//td[@id='topButtonRow']//input[@name='save_new']")
WebElement saveAndNewItemBtn;
//Property name after clicking on 'Save' Item button
@FindBy(xpath = "//div[@id='Name_ileinner']")
WebElement itemNm;
//Method for clicking on 'New Item' button
public void newItemButton(){
//Click on 'New Item' button.
newItemBtn.click();
}
//Method for adding multiple Items
public void addNewItem(String selectItemRecordType,String itemName,String wildCard,String foodRevenueClassificationsName,String beverageRevenueClassificationsName,String quantityCalculationPerPerson){
//Explicit wait to visible the Text
commonActions.waitForVisibility(itemRecordTypeDDB);
//Select Item Record Type from DDB
Select chooseItemRecordType = new Select(itemRecordTypeDDB);
chooseItemRecordType.selectByVisibleText(selectItemRecordType);
//Click on 'Continue' button.
continueBtn.click();
//Enter 'Item' name.
itemNameTxtBox.sendKeys(itemName);
String enteredItemName = itemNameTxtBox.getAttribute("value");
//Parent window id
String parentWindow = driver.getWindowHandle();
//Explicit wait to visible the Text
commonActions.waitForVisibility(revenueClassificationLookupBtn);
//Click on 'Revenue Classification' lookup button.
revenueClassificationLookupBtn.click();
//Explicit wait for 'Number of Windows'
commonActions.waitForNumberOfWindows();
//To get all window's ids
Set<String> allWindows = driver.getWindowHandles();
for(String childWindow:allWindows){
if(!childWindow.equalsIgnoreCase(parentWindow)){
//Focus on Child window.
driver.switchTo().window(childWindow);
//Focus on 'Search Frame' window.
driver.switchTo().frame(searchFrameName);
//Explicit wait to visible the Text
commonActions.waitForVisibility(revenueClassificationsSearchBox);
//Clear the text box
revenueClassificationsSearchBox.clear();
//Explicit wait to visible the Text
commonActions.waitForVisibility(revenueClassificationsSearchBox);
//Enter 'Wildcard' symbols
revenueClassificationsSearchBox.sendKeys(wildCard);
//Explicit wait to visible the Text
commonActions.waitForVisibility(goBtn);
//Click on 'Go' button.
goBtn.click();
//Focus on 'Main' window.
driver.switchTo().defaultContent();
//Explicit wait to visible the Text
commonActions.waitForVisibility(resultFrame);
//Focus on 'Result Frame' window.
driver.switchTo().frame(resultFrame);
//Explicit wait to visible the Text
commonActions.waitForVisibility(revenueClassificationNameFoodLinkTxt);
//Click on 'Food' Revenue Classification.
if(enteredItemName.equalsIgnoreCase(foodRevenueClassificationsName)){
revenueClassificationNameFoodLinkTxt.click();
}
//Click on 'Beverage' Revenue Classification.
else if(enteredItemName.equalsIgnoreCase(beverageRevenueClassificationsName)){
revenueClassificationNameBeverageLinkTxt.click();
}
}
}
//Focus on Parent window.
driver.switchTo().window(parentWindow);
//Select 'Quantity Calculation' from DDB.
Select quantityCalculation = new Select(quantityCalculationDDB);
quantityCalculation.selectByVisibleText(quantityCalculationPerPerson);
if(i < totalItems)
{
saveAndNewItemBtn.click();
i = i + 1;
}
else{
saveItemBtn.click();
commonActions.waitForVisibility(itemNm);
}
}
//Method to compare with 'Available Item Record Types' static text
public String getavailableItemRecordTypesTxtAfterSaveAndNewBtn(){
String availableItemRecordTypesTxt = "";
try{
***availableItemRecordTypesTxt = driver.findElement(By.xpath("//h3[@class='recordTypesHeading']")).getText();***
}
catch (NoSuchElementException exp){
System.out.println("This is exception message " + exp);
}
return availableItemRecordTypesTxt;
}
//Method to compare with 'Property' name
public String getitenNameAfterSaveButton(){
String itenNameAfterSaveButton = driver.findElement(By.xpath("//div[@id='Name_ileinner']")).getText();
return itenNameAfterSaveButton;
}
}
下面是测试类别:
公共类TC_CreateNewItem扩展了BaseClass {
CreateNewItemObjects createNewItem;
ReadAndWriteProperties readwriteprop = new ReadAndWriteProperties();
CommonActions commonActions;
@Test(priority = 1)
public void clickNewItemButton(){
createNewItem = new CreateNewItemObjects();
commonActions = new CommonActions();
commonActions.waitForVisibility(createNewItem.newItemBtn);
createNewItem.newItemButton();
}
@Test(priority = 2,dataProvider = "getNewItemCreationDataThroughExcel")
public void addNewItemsForProperty(String selectItemRecordTypeDDL,String itemNm,String wildCardSymbols,String revenueClassificationsNameFood,String revenueClassificationsNameBeverage,String quantityCalculationEachPerson,String availableItemRecordTypesText,String itenNameAfterSaveBttn){
createNewItem = new createNewItemObjects();
//Executing Object class method
createNewItem.addNewItem(selectItemRecordTypeDDL,itemNm,wildCardSymbols,revenueClassificationsNameFood,revenueClassificationsNameBeverage,quantityCalculationEachPerson);
//Checking whether 'Available Item Record Types' or 'Property Name' available or not
try{
***if(createNewItem.getavailableItemRecordTypesTxtAfterSaveAndNewBtn().equalsIgnoreCase(availableItemRecordTypesText)){***
Assert.assertTrue(true);
logger().info("Item is created successfully.");
}
else if(createNewItem.getitenNameAfterSaveButton().equalsIgnoreCase(itenNameAfterSaveBttn)){
Assert.assertTrue(true);
logger().info("Item is created succussfully.");
}
else{
logger().warn("Item creation is failed.");
Assert.assertTrue(false);
}
}
catch(Exception exp){
exp.printStackTrace();
}
}
//The 'DataProvider' annotation to fetch the data from excel.
@DataProvider
public Object[][] getNewItemCreationDataThroughExcel(){
return ReadAndWriteExcel.getExcelData(readwriteprop.getCompletePropertyCreationExcelPath(),readwriteprop.getItemsMenusTextDataSheetName());
}
}
错误代码:
org.openqa.selenium.NoSuchElementException:否这样的元素:无法找到元素:{“ method”:“ xpath”,“ selector”:“ // h3 [@ class ='recordTypesHeading']”} (会议信息:chrome = 84.0.4147.125) 有关此错误的文档,请访问:https://www.seleniumhq.org/exceptions/no_such_element.html 构建信息:版本:'3.141.59',修订版本:'e82be7d358',时间:'2018-11-14T08:17:03' 系统信息:主机:'DATTAC-WIN8',ip:'10 .75.8.53',操作系统名称:'Windows 10',os.arch:'amd64',os.version:'10 .0',java.version:'1.8 .0_161' 驱动程序信息:org.openqa.selenium.chrome.ChromeDriver 功能{acceptInsecureCerts:false,browserName:chrome,browserVersion:84.0.4147.125,chrome:{chromedriverVersion:84.0.4147.30(48b3e868b4cc0 ...,userDataDir:C:\ Users \ dattac \ AppData \ Loc ...},goog:chromeOptions :{debuggerAddress:localhost:63652},javascriptEnabled:true,networkConnectionEnabled:false,pageLoadStrategy:none,平台:WINDOWS,platformName:WINDOWS,proxy:Proxy(),setWindowRect:true,strictFileInteractability:false,超时:{implicit:0, pageLoad:300000,脚本:30000},unhandledPromptBehavior:关闭并通知,webauthn:virtualAuthenticators:true} 会话ID:6543ce8946621a7081bac5786eabaf73 ***元素信息:{Using = xpath,value = // h3 [@ class ='recordTypesHeading']} 在sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)处 在sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 在sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 在java.lang.reflect.Constructor.newInstance(Constructor.java:423) 在org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) 在org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) 在org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) 在org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) 在org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83) 在org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552) 在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323) 在org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428) 在org.openqa.selenium.By $ ByXPath.findElement(By.java:353) 在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315) 在com.test.qa.pageobjects.CreateNewItemObjects.getavailableItemRecordTypesTxtAfterSaveAndNewBtn(CreateNewItemObjects.java:191) 在com.test.qa.testcases.TC_CreateNewItem_0007.addNewItemsForProperty(TC_CreateNewItem_0007.java:36) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:498) 在org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124) 在org.testng.internal.Invoker.invokeMethod(Invoker.java:583) 在org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719) 在org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989) 在org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125) 在org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109) 在org.testng.TestRunner.privateRun(TestRunner.java:648) 在org.testng.TestRunner.run(TestRunner.java:505) 在org.testng.SuiteRunner.runTest(SuiteRunner.java:455) 在org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450) 在org.testng.SuiteRunner.privateRun(SuiteRunner.java:415) 在org.testng.SuiteRunner.run(SuiteRunner.java:364) 在org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) 在org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84) 在org.testng.TestNG.runSuitesSequentially(TestNG.java:1208) 在org.testng.TestNG.runSuitesLocally(TestNG.java:1137) 在org.testng.TestNG.runSuites(TestNG.java:1049) 在org.testng.TestNG.run(TestNG.java:1017) 在org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132) 在org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236) 在org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
解决方法
由于未处理异常而失败。
每次致电此行:
if(createNewItem.getavailableItemRecordTypesTxtAfterSaveAndNewBtn().equalsIgnoreCase(availableItemRecordTypesText)){
您正在运行此方法:
//Method to compare with 'Available Item Record Types' static text
public String getavailableItemRecordTypesTxtAfterSaveAndNewBtn(){
String availableItemRecordTypesTxt = driver.findElement(By.xpath("//h3[@class='recordTypesHeading']")).getText();
return availableItemRecordTypesTxt;
}
在您的评论中,您说您执行了7次,但由于文本不存在,因此在上一次迭代中失败。你说:
当脚本单击“保存”按钮时,UI会有所不同,并且 没有“保存并新建”按钮。
我想您正在期待,因为此方法位于IF
中(从第一个代码块开始),如果对象不存在,它将不返回任何内容。但是,硒不能那样工作。
实际上发生的是,您要让硒查看元素是否存在,并且硒是否找不到对象,它会抛出NoSuchElementException
使用硒的最佳方法是仅对预期对象编程代码。检查对象-不-存在会更加困难,因为您需要确保已为页面准备就绪,所有脚本都已执行并完成而充分等待(隐式或显式等待时间)返回所有数据。这通常会导致脚本花费时间。如果您不等那么多时间,就会得到 false-passes ,这在测试世界中是非常糟糕的。例如,假设您将隐式等待时间设置为30秒-并想验证某个元素不存在,则每次调用该元素都必须等待30秒。如果该方法随后被多个脚本调用,则总执行时间将迅速增加。
也就是说-如果您想要快速解决方案。像这样向您的代码添加错误处理:
public String getavailableItemRecordTypesTxtAfterSaveAndNewBtn(){
//create a new blank string
String availableItemRecordTypesTxt = "";
try
{
// only set the string if the object exists
availableItemRecordTypesTxt = driver.findElement(By.xpath("//h3[@class='recordTypesHeading']")).getText();
}
catch (NoSuchElementException ex)
{
//Allow this error the be thrown but not stop your test
//error handle here - e.g. reporting or another action
}
return availableItemRecordTypesTxt;
}
这将使您的对象出错,并且如果不存在该对象,该方法将不返回任何文本,并且从理论上讲,如果该文本不存在,则继续进行下一个文本。
根据评论进行更新。
错误处理到位,但未捕获到异常。 我相信您添加了错误的例外。要明确,并在您的下层方法中替换此行:
catch (org.openqa.selenium.NoSuchElementException exp){
我已经在问题的简化版本上运行了一些代码。 我添加了一个xpath,该xpath显然将不存在,并且代码捕获了错误并且不返回任何文本。
这是代码:
@Test
public void demo()
{
String WhatIsTheReturn = getavailableItemRecordTypesTxtAfterSaveAndNewBtn();
System.out.println("the return is... " + WhatIsTheReturn);
}
public String getavailableItemRecordTypesTxtAfterSaveAndNewBtn(){
String availableItemRecordTypesTxt = "";
try{
availableItemRecordTypesTxt = driver.findElement(By.xpath("//a[text()='I do not exist']")).getText();
}
catch (org.openqa.selenium.NoSuchElementException exp){
System.out.println("Excpetion was handled!");
}
return availableItemRecordTypesTxt;
}
这是输出(捕获到异常,返回为空)
,期望得到处理!
返回是...
选择器值可能错误。 尝试使用硒IDE与该特定元素进行交互,然后使用IDE显示的选择器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。