要如何知道某一個物件在網頁裡的狀態?
sample code how to verify element
- ispresent
- isvisible
- isenable
- textpresent
in Selenium WebDrvier using Java
To check Element Present:
if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
Or
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
To check Visible:
if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
To check Enable:
if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}
To check text present
if(driver.getPageSource().contains("Text to check")){
System.out.println("Text is present");
}else{
System.out.println("Text is absent");
}
上面是 java 的版本,要改成python 就改用 is_displayed() 就可以了。
範例:
def login():
user_elements = browser.find_elements_by_xpath('//input[contains(@name, "user")]')
for user in user_elements:
if user.is_displayed():
if user.is_enabled():
user.send_keys(username)
pass_elements = browser.find_elements_by_xpath('//input[contains(@name, "pass")]')
for passw in pass_elements:
if passw.is_displayed():
if passw.is_enabled():
passw.clear()
passw.send_keys(password + Keys.RETURN) #Crashes here
time.sleep(4)
return