1

I am using Python 3 and Selenium to automate browser activity. On the page I am working on I have a button which when clicked loads a drop down menu. However upon inspecting I believe the dropdown menu is generated after the button is clicked as I do not see the html for the menu on page load.

I am using the following code

driver.get(path)
sleep(1)
try:
    driver.find_element_by_id("DROPDOWN").click()
    sleep(8)
    driver.find_element_by_xpath('//button[text()="Account"]').click()
    print("button clicked")
except:
    print("no button to click")
sleep(1)
browser.quit()

The html

<button class="_19rM-p " id="DROPDOWN">
    <i class="_F-AgkVkVa  icon icon-menu"></i>
    <span class="_2Q7bh">Menu</span>
</button>

This menu is loaded after presumably via JS, the button I am trying to click is text Account

<div class="_2ID5Vy" role="menu">
    <div class="_2ID5Vy">
        <div class="_2pcjK9c" style="display: block;"></div>
        <div><span class="_4cdfLigUWzeeVcPzzbe78">User Menu</span></div>
    </div>
    <div class="_49I5s">
        <button role="button" class="_2s6F0RequP0">Account</button>
    </div>
<div>

This loads up the website, and clicks on the dropdown menu. I see the button load in the drop down menu which I am trying to get the browser to click but it never does click. I am not sure what is causing this. It might be that the html is added after page load.

What can I do to click the button?

Thanks.

Edit Updated code to include html.

vitaliis
  • 4,082
  • 5
  • 18
  • 40
  • Your XPath seems to work fine for that html and 8 seconds should be long enough. The only thing i could suggest is if [click isn't working](https://stackoverflow.com/questions/11676790/click-command-in-selenium-webdriver-does-not-work). Are you running selenium headless? – Codesidian Aug 17 '21 at 19:19

1 Answers1

2

time.sleep that you use may be not efficient enough. Add explicit wait. For this import:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

And use this way:

driver.find_element_by_id("DROPDOWN").click()
account_btn = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()="Account"]")))
account_btn.click()
print("button clicked")

Also, you can try clicking with CSS selector. For this button one of its options will be: ._2s6F0RequP0

account_btn = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "._2s6F0RequP0")))
account_btn.click()

Remember that your locators have to be unique. In your html code your locator is unique, but maybe on the page you are viewing are more buttons with such text.

vitaliis
  • 4,082
  • 5
  • 18
  • 40