使用硒webdriver自動執行腳本時,.is dispayed()命令不起作用if else語句。 如果if語句的條件爲真,那麼它工作正常。但是如果條件不成立,代碼不會移動到else語句。在使用selenium webdriver自動執行腳本時,**。is dispayed()**命令在** if else語句中不起作用**
package module17;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Dice {
static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Automation Software\\chromedriver_win32\\chromedriver_update.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.get("http://www.dice.com/");
Thread.sleep(15000);
driver.findElement(By.xpath("//*[@alt='Close']")).click();
driver.findElement(By.xpath("//*[@id='search-field-keyword']")).sendKeys("Selenium WebDriver");
WebElement Place =driver.findElement(By.xpath("//input[@placeholder='Location']"));
Place.clear();
driver.findElement(By.xpath("//button[contains(text(),'Find Tech Jobs')]")).click();
WebElement PageNumber = driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'2')]"));
int i=2;
while(i<=44)
{
try
{
if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).isDisplayed() )
{
driver.findElement(By.xpath("//*[@id='dice_paging_top']//*[contains(text(),'"+i+"')]")).click();
Thread.sleep(5000);
i= i+5;
}
else if(driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).isDisplayed())
{
driver.findElement(By.xpath("//*[@id='dice_paging_top']//a[@title='Go to next page']")).click();
}
else
{
driver.quit();
}
}
catch (Exception e)
{
System.out.println("Exception");
}
}
}
}
錯!如果元素存在並且不顯示,那麼它返回false。只有元素不存在時它纔會拋出錯誤。這個問題可以用更有效的方法解決,但沒有人仍然沒有給出正確的答案。 – Gopal
@Gopal我們可以用更有效的方式解決它,但是我修復了它的代碼。如果元素不存在於頁面中,則driver.findelement本身將拋出異常,即NoSuchElementException。糾正我,如果我worng。 – Akarsh
是的我同意這也是我所說的,但isDisplayed不會拋出錯誤,如果元素存在並且不可見,它將返回false,但是您的回覆主要表示它會拋出錯誤,這是錯誤的。 – Gopal