I have an issue with Selenium Webdriver. I am running my automated test against a web application and have a test to check visibility of an element. When I run the same line of script in CLI
, the element is found and is_displayed()
returns "TRUE" but When I run it with other test cases through my Python IDE, is_displayed()
returns False
.
I tried implicit and explicit waits but wait is not the issue and the element is already loaded.
Here is the test case in my test script:
def test_image_element_icon_is_displayed(self):
self.assertTrue(self.driver.find_element_by_css_selector("#Image").is_displayed(),msg="Image is not displayed")
And this is script I run in CLI:
driver.find_element_by_css_selector("#Image").is_displayed()
Is there any way that I can prevent this false negative? Maybe changing the element selector I am currently using?
Here is the HTML of my Image element:
<div ng-click="applyDataElement(toolbarButton.type, toolbarButton.id)" class="frame-click ng-scope" ng-repeat="toolbarButton in toolbar">
<div class="frame-box" ng-attr-id="{{toolbarButton.id}}" id="Image">
<div class="draggable-box">
<div bind-html-unsafe="toolbarButton.icon" class="draggable-icon ng-binding"><i class="fa fa-picture-o"></i></div>
<div class="draggable-label ng-binding">Image</div>
</div>
</div>
</div>
I am pretty sure this id cannot be unique since it is in ng-repeat
and it's probably loading more than one elements with same id which is not safe to use.
With that being said and since, you also mentioned element load is not an issue, it safe to assume that the selector is probably returning some other element which is actually hidden. I experienced something similar before where selenium actually found the element which was hidden and was not the intended one. You can actually use len()
with find_elements_by_css_selector()
to see how many elements were returned.
Use ng-attr-id="{{toolbarButton.id}}"
or whatever displayed on client in cojuntion with [id='image'][ng-attr-id='something']
as cssSelector
The key difference between running the code in the Python terminal and running it as a script is that on terminal you have pauses/delays between every line you execute - this gives the page time to process asynchronous requests, update the DOM etc. In your test code, you need to wait for the element to become visible:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
image = wait.until(EC.visibility_of_element_located((By.ID, "Image")))
来源:https://stackoverflow.com/questions/29462888/selenium-webdriver-false-negative-result-for-testing-visibility-of-an-element