当我测试phptravel网站并尝试单击带有以下代码的 myaccount 链接时。 Selenium在执行期间返回 ElementNotVisibleException 。我错过了什么?
源代码
public void login(WebDriver driver) {
driver.navigate().to("https://www.phptravels.net/");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/nav/div/div[1]/a")));
// Error on here
myAccount.click();
WebDriverWait myAccountWait = new WebDriverWait(driver, 10);
myAccountWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"li_myaccount\"]/ul")));
loginLink.click();
WebDriverWait loginWait = new WebDriverWait(driver, 10);
//loginWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\\\"loginfrm\\\"]/div[1]/div[5]/div/div[1]/input")));
username.sendKeys("user@phptravels.com");
password.sendKeys("demouser");
loginBtn.click();
}
答案 0 :(得分:0)
Modify the code as below:
On your WebDriverWait keep the xpath as below with By type:
By myAccountBy = By.xpath("//ul[@class='nav navbar-nav navbar-right']/ul/li[1]/a");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(myAccountBy));
OR
Hardcode the xpath like below.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.Xpath("//ul[@class='nav navbar-nav navbar-right']/ul/li[1]/a")));
Then keep the same xpath for myAccount WebElement as below
@FindBy(xpath="//ul[@class='nav navbar-nav navbar-right']/ul/li[1]/a")
public WebElement myAccount;
In short, to click the MyAccount you have to keep this xpath
//ul[@class='nav navbar-nav navbar-right']/ul/li[1]/a
答案 1 :(得分:0)
myAccount webElement is not initialized in your code.
In case you want to click on My account link you can use this :
WebElement myAccount = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='collapse']/descendant::ul[3]/li[@id='li_myaccount']/a")));
myAccount.click();
Note that you can't use link Text as that is text nodes .
答案 2 :(得分:0)
First you need to create WebElement
then use elementToBeClickable
Expected Condition for the same this way you can resolve the issue
WebElement myAccount = driver.findElement("Your locator");
Now use wait
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(myAccount));
myAccount.click();
Also maximize the browser.
答案 3 :(得分:0)
始终最好的做法是在加载URL之后添加显式等待。我可以根据以下经过修改的XPath单击“帐户”链接。
Xpath: //nav//li[@id='li_myaccount']//a
工作代码:
driver.get("https://www.phptravels.net/");
WebDriverWait wait=new WebDriverWait(driver,10);
//wait is added in order to complete the page loading
wait.until(ExpectedConditions.titleContains("PHPTRAVELS"));
driver.findElement(By.xpath("//nav//li[@id='li_myaccount']//a")).click();
答案 4 :(得分:-3)