我在“显式等待”中遇到了麻烦,但它并不总是有效。他们会随机失败,我不确定为什么。我正在击中找不到元素或陈旧元素。我该怎么做才能使它们更可靠?
public class FrameRegisterAccount extends BasicTests
{
// Generates Email
String userName = ""+(int)(Math.random()*Integer.MAX_VALUE);
String emailID = "Otto"+userName+"@gmail.com";
@Test (priority=1)
public void NewAccount() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
WebElement signButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='button-sign']")));
signButton.click();
log.info("New Account Creation Screen Opened");
// Fill out Form
WebElement nameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("first_name")));
nameField.sendKeys("Otto");
driver.findElement(By.name("last_name")).sendKeys("Mation Tester");
driver.findElement(By.name("phone_number")).sendKeys("555-555-3231");
driver.findElement(By.name("listings")).sendKeys("4");
// Enter Email and Password
driver.findElement(By.xpath("//input[@name='email']")).clear();
driver.findElement(By.xpath("//input[@name='email']")).sendKeys(emailID);
driver.findElement(By.xpath("//input[@name='password']")).clear();
driver.findElement(By.xpath("//input[@name='password']")).sendKeys("password");
// Click buttons
driver.findElement(By.xpath("//div[@class='input input-term']//div[@class='checkbox-icon']")).click();
driver.findElement(By.xpath("//span[contains(text(),'Sign Up')]")).click();
Thread.sleep(3000);
log.info("New Account Created");
}
@Test (priority=2)
public void ChangePassword() {
// Wait for Dashboard Button
WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
WebElement dashButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class,'success-dashboard')]")));
dashButton.click();
log.info("Go to Dashboard Button Pressed");
// Change Password
WebElement proNameX = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='sidebar-top-item']")));
proNameX.click();
WebElement changePass = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='nf-change-password-btn']")));
changePass.click();
//driver.findElement(By.xpath("//div[@id='nf-change-password-btn']")).click();
driver.findElement(By.name("old_password")).sendKeys("password");
driver.findElement(By.name("new_password")).sendKeys("wordpass");
driver.findElement(By.name("new_password2")).sendKeys("wordpass");
driver.findElement(By.xpath("//button[@type='button']")).click();
log.info("Password Change Completed");
}
Stacktrace:
org.openqa.selenium.StaleElementReferenceException:
stale element reference: element is not attached to the page document
(Session info: headless chrome=72.0.3626.109)
(Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.14.88-88.76.amzn2.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42199}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true}
Session ID: 1a448c188bc68362fa3dc7858ee770b3
at registerAuto.FrameRegisterAccount.ChangePassword(FrameRegisterAccount.java:57)
堆栈2:
org.openqa.selenium.TimeoutException: 预期条件失败:等待元素可单击:By.xpath:// div [@ id ='sidebar-top-item'](尝试15秒,间隔2500毫秒) 构建信息:版本:'3.141.59',修订版本:'e82be7d358',时间:'2018-11-14T08:17:03' 系统信息:主机:'ip-172-31-36-12.us-west-2.compute.internal',ip:'172.31.36.12',操作系统名称:'Linux',os.arch:'amd64' ,os.version:“ 4.14.88-88.76.amzn2.x86_64”,java.version:“ 1.8.0_131” 驱动程序信息:org.openqa.selenium.chrome.ChromeDriver 功能{acceptInsecureCerts:false,acceptSslCerts:false,applicationCacheEnabled:false,browserConnectionEnabled:false,browserName:chrome,chrome:{chromedriverVersion:2.46.628388(4a34a70827ac54 ...,userDataDir:/tmp/.org.chromium.Chromium ... },cssSelectorsEnabled:true,databaseEnabled:false,goog:chromeOptions:{debuggerAddress:localhost:42977},handlesAlerts:true,hasTouchScreen:false,javascriptEnabled:true,locationContextEnabled:true,mobileEmulationEnabled:false,nativeEvents:true,networkConnectionEnabled:false, pageLoadStrategy:正常,平台:LINUX,平台名称:LINUX,代理:Proxy(),可旋转:false,setWindowRect:true,strictFileInteractability:false,takesHeapSnapshot:true,takesScreenshot:true,超时:{隐式:0,pageLoad:300000,脚本:30000},unexpantedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:72.0.3626.109,webStorageEnabled:true} 会话ID:7b255ab6a2cf5b58cf3919904e703b2a 完全没有StagingAutomation.FrameRegisterAccountStaging.ChangePassword(FrameRegisterAccountStaging.java:55)
答案 0 :(得分:0)
StaleElementReference异常在您尝试交互的元素不再在dom中或已过时时出现。因此,您需要刷新页面,然后再次获取该元素,它将起作用。
因此,请在要获取异常的元素之前添加AppContainer.js:
class CompanyNavWrapper extends Component {
constructor(props){
super(props);
}
render(){
return (
<CompanyNavigator screenProps={{ rootNavigation: this.props.navigation}} />
)
}
}
const CompanyNavigator = createStackNavigator({
CompanyList: {
screen: CompanyList,
navigationOptions: ({ navigation }) => ({
title: "Companies"
})
},
PartnershipEdit: {
screen: PartnershipEdit,
navigationOptions: ({ navigation }) => ({
title: "Partnership Edit",
headerMode: 'screen'
})
}
},
{
headerMode: 'screen'
}
);
export const SignInNavigator = createDrawerNavigator({
Menu: {
screen: Menu,
navigationOptions: {
title: "Menu",
}
},
PartnershipList: {
screen: PartnershipList,
navigationOptions: ({ navigation }) => ({
title: "Partnerships",
headerLeft: <Icon name="three-bars" size={35} onPress={ () => navigation.navigate('DrawerOpen') } />
})
},
Company: {
screen: CompanyNavWrapper,
navigationOptions:{
title:'Companies'
}
}
}, {
contentComponent:(props) => (
<View style={{flex:1}}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems {...props} />
<TouchableHighlight onPress={async () => {
await deleteUser();
NavigationService.navigate('Auth');
}} underlayColor='#ffffff'>
<Text style={{marginLeft: 15, marginTop: 10, color: '#000000', fontWeight: 'bold', backgroundColor: '#ffffff'}}>Logout</Text>
</TouchableHighlight>
</SafeAreaView>
</View>
),
drawerOpenRoute: 'DrawerOpen',
drawerCloseRoute: 'DrawerClose',
drawerToggleRoute: 'DrawerToggle'
},{
headerMode: 'float',
navigationOptions: ({ navigation }) => ({
headerLeft: <Icon name="three-bars" size={35} onPress={ () => navigation.navigate('DrawerOpen') } />,
})
}
);
export const mainNav = createStackNavigator({
DrawerStack: { screen: SignInNavigator }
},
{
headerMode: 'float',
navigationOptions: ({navigation}) => ({
headerLeft: <Icon name="three-bars" size={18} style={{paddingLeft: 10}} onPress={ () => { navigation.state.index == 0 ? navigation.navigate('DrawerOpen') : navigation.navigate('DrawerClose') } } />,
headerStyle: { backgroundColor: '#ffffff', height: 20 },
headerTitleStyle: {
color: '#000000',
textAlign: 'center',
alignSelf: 'center',
flex: 0.85
},
headerRight: <View/>
})
}
)
export const SignedOutNavigator = createStackNavigator(
{
Login: { screen: Login },
Register: { screen: Register },
ForgotPassword: {screen: ForgotPassword },
ForgotPasswordReset: {screen: ForgotPasswordReset }
},
{
headerMode: 'none',
cardStyle: { backgroundColor: 'transparent' }
}
);
export const AppNavigator = createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: mainNav,
Auth: SignedOutNavigator
},
{
initialRouteName: 'AuthLoading',
}
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
app.js:
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<Provider store={store}>
<AlertProvider>
<AppContainer
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
</AlertProvider>
</Provider>
</View>
);
}
}
行代码,然后对该元素进行操作,即可正常工作。
答案 1 :(得分:0)
此代码出现“没有这样的元素:无法找到元素”错误。它找不到“ // div [@ class ='airgms-input airgms-input-text'] // input [@ type ='text']” xpath。我尝试了不同的xpath。
@Test(priority = 1)
public void LogIns() {
driver.findElement(By.id("login-email")).sendKeys("admin.test@gmail");
driver.findElement(By.id("login-password")).sendKeys("password");
driver.findElement(By.xpath("//button[@href='javascript:void(0);']")).click();
log.info("Log in Successful");
}
@Test(priority = 2)
public void LoadInboxTab() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 20, 2000L);
WebElement InboxTab = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='team-member-sections']//div[1]")));
InboxTab.click();
Thread.sleep(3000);
log.info("Inbox Opened Successfully");
Stacktrace
org.openqa.selenium.NoSuchElementException: 没有这样的元素:无法找到元素:{“ method”:“ xpath”,“ selector”:“ // div [@ class ='airgms-input airgms-input-text'] // input [@ type ='text ']“} (会议信息:headless chrome = 72.0.3626.109) (驱动程序信息:chromedriver = 2.46.628388(4a34a70827ac54148e092aafb70504c4ea7ae926),平台= Linux 4.14.88-88.76.amzn2.x86_64 x86_64)(警告:服务器未提供任何堆栈跟踪信息) 命令持续时间或超时:0毫秒 有关此错误的文档,请访问:https://www.seleniumhq.org/exceptions/no_such_element.html 构建信息:版本:'3.141.59',修订版本:'e82be7d358',时间:'2018-11-14T08:17:03' 系统信息:主机:'ip-172-31-36-12.us-west-2.compute.internal',ip:'172.31.36.12',操作系统名称:'Linux',os.arch:'amd64' ,os.version:“ 4.14.88-88.76.amzn2.x86_64”,java.version:“ 1.8.0_131” 驱动程序信息:org.openqa.selenium.chrome.ChromeDriver 功能{acceptInsecureCerts:false,acceptSslCerts:false,applicationCacheEnabled:false,browserConnectionEnabled:false,browserName:chrome,chrome:{chromedriverVersion:2.46.628388(4a34a70827ac54 ...,userDataDir:/tmp/.org.chromium.Chromium ... },cssSelectorsEnabled:true,databaseEnabled:false,goog:chromeOptions:{debuggerAddress:localhost:40837},handlesAlerts:true,hasTouchScreen:false,javascriptEnabled:true,locationContextEnabled:true,mobileEmulationEnabled:false,nativeEvents:true,networkConnectionEnabled:false, pageLoadStrategy:正常,平台:LINUX,平台名称:LINUX,代理:Proxy(),可旋转:false,setWindowRect:true,strictFileInteractability:false,takesHeapSnapshot:true,takesScreenshot:true,超时:{隐式:0,pageLoad:300000,脚本:30000},unexpantedAlertBehaviour:忽略,unhandledPromptBehavior:忽略,版本:72.0.3626.109,webStorageEnabled:true} 会话ID:d31d6d2119c6586877f2f9ba5e73ee0d ***元素信息:{使用= xpath,值= // div [@ class ='airgms-input airgms-input-text'] // input [@ type ='text']} 完全没有StagingAutomation.FramePriceAvailabilityStaging.RevertPriceAvailandChanges(FramePriceAvailabilityStaging.java:122)