Home > Net >  xpath for click to a button - python/selenium
xpath for click to a button - python/selenium

Time:02-14

I'm trying to access a homepage, make login, click the login button and click a button (in the second page) using python/selenium.

The login button I wrote using Xpath and it's working well. The browser opens, writes user and login and click the login button.

Unfortunately, in the next page I'm not able to click on the button that I need to. It didn't work using Xpath and I can't understand why. The html is completely different from the first button, the button name is 'Reservar' and it is inside a class named <app-menu__menu>, written as:

<a href="/Services" id="advanced" >
                    
                    <span>Reservar</span>
                </a>

The xpath I got and tried:

xpath = "//*[@id="advanced"]"

Then I tried a second verion (it was gotten as the second line code xpath):

xpath = "//*[@id="advanced"]/span"

When I first tried to used them, I got an error. Then I change the "" to ' ' and the error was gone. But the program can't locate the button.

I'm using google-chrome, ubuntu, python3 and selenium package:

driver.find_element_by_xpath(xpath).click()

Thanks for any help.

CodePudding user response:

You probably missing a delay / wait.
After clicking the submit / login button on the login page it takes some time to make the internal page loaded.
The recommended way to do that is to use Expected Conditions explicit waits, something like this:

wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='advanced']"))).click()

To use the wait object here you will need to import the following inports:

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

And to initialize the wait object with

wait = WebDriverWait(driver, 20)

You will have to validate your locator is unique. As well as to validate the element you are trying to access is not inside iframe and not in a new window / tab etc.

  • Related