Home > Software engineering >  Which expected_conditions to use?
Which expected_conditions to use?

Time:03-03

I have this list on a website using Python's Selenium.

enter image description here

Clicking an item opens a sublist where you can click multiple buttons. I click these buttons with JavaScript so that the sublist never opens. This method is faster.

...
driver.execute_script(button)

My question is which expected_conditions should I use to wait for the buttons to appear in the DOM so that I can select it with JavaScript?

expected_conditions.element_to_be_clickable (what I use all the time) isn't the right answer.

CodePudding user response:

In case you are using JavaScript to click those elements you do not need to wait for these elements clackability or visibility, presence will be enough in this case. So, you can use presence_of_element_located method here.
I would advice never use JavaScript clicking with Selenium until you have no alternative since Selenium is simulating human GUI activities which in 99.9% cases may and should be done with selenium .click() method. In case you can not do it with this method it will normally mean human will not be able to perform this action via GUI, so this is normally not what we want to do testing the GUI functionality with Selenium.

CodePudding user response:

As you are not expanding the items and sublist being invisible you are invoking click() on multiple buttons, WebDriverWait for visibility_of_element_located() and element_to_be_clickable() will always fail.


Solution

In such cases, your best bet would be to induce WebDriverWait for the presence_of_element_located() as follows:

element = WebDriverWait(driver, 20).until(expected_conditions.presence_of_element_located((By.XPATH, "element_xpath']")))
driver.execute_script(""arguments[0].click();", element)

In a single line:

driver.execute_script(""arguments[0].click();", WebDriverWait(driver, 20).until(expected_conditions.presence_of_element_located((By.XPATH, "element_xpath']"))))

Another JavaScript based alternative would be:

driver.execute_script("document.getElementsByClassName('theClassName')[0].click()")
  • Related