Reputation: 61
I am trying to click on this button so that I can proceed to the next page but doesn't seem to be working for me. I am trying to click on the 'Search for an inspection report' button.
This is the xpath for this source. //[@id="btnOK"] . And so I was trying to use driver.find_element_by_xpath('//[@id="btnOK"]').click() and it gives me an error saying unable to locate element.
Here is the link to the site. https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise
Any help would be great.
Upvotes: 1
Views: 247
Reputation: 4482
Alternative solution using webdriver wait:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('<PATH_TO_CHROMEDRIVER>', options=chrome_options)
# load page via selenium
wd.get("https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise")
# wait for iframe, switch to it
frame = WebDriverWait(wd, 30).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"iframe-form")))
# wait for button, scroll to it, click it
btn = WebDriverWait(wd, 30).until(EC.presence_of_element_located((By.ID, 'btnOK')))
wd.execute_script("arguments[0].scrollIntoView();", btn)
wd.execute_script("arguments[0].click();", btn)
Upvotes: 0
Reputation: 5531
It is because the button is present within a different iframe
. In order to click that button, u have to switch focus to that iframe
. This is how u do it:
iframe = driver.find_element_by_id("iframe-form")
driver.switch_to.frame(iframe)
btn = driver.find_element_by_xpath('//*[@id="btnOK"]')
btn.click()
Plus, another thing to note is that the xpath
u have provided is wrong. U have missed a *
in the xpath
. The right xpath
is '//*[@id="btnOK"]'
.
Complete code:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.halton.ca/For-Residents/Food-Safety/Dinewise/Search-Directory-of-Food-Premises-Dinewise')
iframe = driver.find_element_by_id("iframe-form")
driver.switch_to.frame(iframe)
btn = driver.find_element_by_xpath('//*[@id="btnOK"]')
btn.click()
Hope that this helps.
Upvotes: 1