【问题标题】:VisibilityOfElementLocated Vs presenceOfElementLocatedVisibilityOfElementLocated 与 PresenceOfElementLocated
【发布时间】:2016-10-28 13:55:00
【问题描述】:
考虑一下:
val element = ...
String str = element.getAttribute("innerHTML")
所以如果我只想得到这个value 是否足以使用presenceOfElementLocated() 而不是visibilityOfElementLocated() ?
【问题讨论】:
标签:
selenium
selenium-webdriver
webdriver
webdriverwait
expected-condition
【解决方案1】:
如果只想获取值presenceOfElementLocated就可以提取值了。
visibilityOfElementLocated 用于测试目的。例如,当你以某种方式与元素交互时,看看它会发生什么。
【解决方案3】:
presenceOfElementLocated()
presenceOfElementLocated() 是检查页面 DOM 上是否存在元素的期望。这并不一定意味着该元素是可见的。
public static ExpectedCondition<WebElement> presenceOfElementLocated(By locator)
Parameters:
locator - used to find the element
Returns:
the WebElement once it is located
visibilityOfElementLocated()
visibilityOfElementLocated() 是检查元素是否存在于页面的 DOM 上并且可见的期望。可见性是指元素不仅显示出来,而且高度和宽度都大于0。
public static ExpectedCondition<WebElement> visibilityOfElementLocated(By locator)
Parameters:
locator - used to find the element
Returns:
the WebElement once it is located and visible
这个用例
要使用Selenium 获取innerHTML 的值,理想情况下,该元素需要可见,而不仅仅是存在。所以你必须使用visibilityOfElementLocated()。
基于java 的有效代码块将是:
-
使用visibilityOfElementLocated():
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("elementCssSelector")));
System.out.println(element.getAttribute("innerHTML"));
-
在一行中:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("elementCssSelector"))).getAttribute("innerHTML"));
基于python 的有效代码块将是:
-
使用visibility_of_element_located():
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css_selector")))
print(element.get_attribute("innerHTML"))
-
在一行中:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css_selector")))).get_attribute("innerHTML"))
基于c# 的有效代码块将是:
-
使用ElementIsVisible():
var element = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("ElementCssSelector")));
Console.WriteLine(element.GetAttribute("innerHTML"));
-
在一行中:
Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("ElementCssSelector"))).GetAttribute("innerHTML"));