Search code examples
pythonselenium-webdriverxpath

Selenium "Unable to locate element" with LINK_TEXT or XPATH


I'm using this code...

class Browser:
    browser, service = None, None

    def __init__(self, driver:str):
        self.service = Service(driver)
        self.browser = webdriver.Edge() #webdriver.Edge(service=self.service)

    def open_page(self, url: str):
        self.browser.get(url)

    def close_browser(self):
        self.browser.close()

    def add_input(self, by: By, value: str, text: str):
        field = self.browser.find_element(by=by, value=value)
        field.send_keys(text)
        time.sleep(1)

    def click_button(self, by: By, value: str):
        button = self.browser.find_element(by=by, value=value)
        button.click()
        time.sleep(1)

    def login_kelio(self, user: str, password: str):
        self.add_input(by=By.ID, value="username", text=user)
        self.add_input(by=By.ID, value="password", text=password)
        self.click_button(by=By.XPATH, value='//input[@value="Confirm"]')
        self.click_button(by=By.XPATH, value='//div[@type="PortailVignetteLienExec"][1]')
        element = WebDriverWait(self.browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//*[contains(text(), "Consultar balance")]')))
        self.browser.execute_script("arguments[0].click();", element)

To click this button with -Consultar balance-

<a class="boutonAction defaultActionBouton" href="javascript:void(0)" onclick="javascript:fcDoAction('AFFICHER__CD')">Consultar balance</a>

But i always get errors either with XPATH or LINK_TEXT

I.E:

"NoSuchElementException: Message: no such element: Unable to locate element:"

Here is the absolute path to the element:

/html/body/div#bwtcontainer/div/div/div/div/div/div/div/div/div/div/div/div/iframe/html/body/form#formAction/table#tableContenu/tbody/tr/td/div.contenu/table/tbody/tr/td/div#badgeuseVirtuelleGTP/table/tbody/tr/td/fieldset/table/tbody/tr/td/a.boutonAction.defaultActionBouton


Solution

  • Switching to the iframe before clicking the button solved the issue, here is how i did it.

    wait = WebDriverWait(self.browser, 5)
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME,'iframe')))
    element = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'Consultar balance')))
    self.browser.execute_script("arguments[0].click();", element)
    

    Thanks to @Shawn.