Home > Enterprise >  Unable to locate element: {"method":"xpath","selector":"//div[@cl
Unable to locate element: {"method":"xpath","selector":"//div[@cl

Time:01-09

I have this website am trying to click on a button in selenium python but it keeps telling me it cant locate the element both implicitly and explicit wait could not make it work. Please any guidance would be appreciated. Below is what i have done:

import time
import unittest

from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By

import time

from selenium.webdriver.support.wait import WebDriverWait


class TestButton(unittest.TestCase):

    def test_button(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://www.moneyhelper.org.uk/en/money-troubles/coronavirus/use-our-money-navigator-tool')
        time.sleep(3)
        
        """clicking to close a cooking popup"""
        self.driver.find_element(By.XPATH, '//*[@id="ccc-notify-accept"]').click()
        time.sleep(3)
        
        """the button which is an anchor tag i have been trying to click"""
        self.driver.find_element(By.XPATH, "//div[@class='landing__actions']//a").click()
        time.sleep(5)

    def tearDown(self):
        self.driver.quit()


if __name__ == "__main__":
    unittest.main()

CodePudding user response:

There is an iframe before //div[@class='landing__actions']//a and you need to switch to this iframe

just try it:

"""clicking to close a cooking popup"""
    self.driver.find_element(By.XPATH, '//*[@id="ccc-notify-accept"]').click()
    time.sleep(3)

    iframe = self.driver.find_element(By.XPATH, '//iframe[@title="Money Navigator tool"]')
    self.driver.switch_to.frame(iframe)

    """the button which is an anchor tag i have been trying to click"""
    self.driver.find_element(By.XPATH, "//div[@class='landing__actions']//a").click()
    time.sleep(5)

CodePudding user response:

It's inside a iframe, you need switch it first using .switch_to.frame(iframe reference):

...

iframe = self.driver.find_element(By.CSS_SELECTOR, '.cmp-embed__iframe')
        
"""the button which is an anchor tag i have been trying to click"""
self.driver.switch_to.frame(iframe)
self.driver.find_element(By.XPATH, "//div[@class='landing__actions']//a").click()
time.sleep(5)
  • Related