visibilityOfElementLocated Vs visibilityOf

2020-03-04 08:52发布

问题:

When i tried to run below code, visibilityOfElementLocated works perfectly fine and webdriver waits for the element with given time.

dr.get("http://www.seleniumframework.com/Practiceform/");
WebDriverWait wait=new WebDriverWait(dr,30);
WebElement we = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Element5")));

but the same way if i use visibilityOf, it gives me

NoSuchElementException

WebElement we = wait.until(ExpectedConditions.visibilityOf(dr.findElement(By.linkText("Element3"))));

Can you explain me why i am getting this exception?

回答1:

but the same way if i use "visibilityOf",it gives me NoSuchElementException

Actually, you are getting Exception by this line of code dr.findElement(By.linkText("Element3")), in your provided code this line will execute first and if element will be find then ExpectedConditions.visibilityOf() callable will execute.

FYI, WebDriver.findElement() either throws exception or returns a WebElement.

visibilityOfElementLocated Vs visibilityOf :-

  • visibilityOfElementLocated is used for checking that an element is present on the DOM of a page and visible. Means it uses By object instead of WebElement object with callable function to find that element first then check that element is visible or not.

  • visibilityOf is used for checking that an element, known to be present on the DOM of a page, is visible. Means you have already found that element and just check only for that visibility.



回答2:

According to this:

visibilityOf: Does not check for presence of the element as the error explains it.

visibilityOfElementLocated: Checks to see if the element is present and also visible. To check visibility, it makes sure that the element has a height and width greater than 0.