Home > OS >  Python Selenium unable to select button in iframe
Python Selenium unable to select button in iframe

Time:07-15

I'm trying to use selenium 4 to click on a button in an iframe to expose the hidden input fields. Taking hints from the answers here and here, I'm still not quite able to click the desired Vote button on the source site.

Source Site

Python 3.10.5

Imports:

import selenium.webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Current code:

driver = selenium.webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get('https://pnccontests.secondstreetapp.com/ChasChoice_2022/gallery/336759126?group=417500')

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element(By.XPATH, """//*[@id="tncms-block-544689"]/p/iframe""")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ember2408"]/div[1]/div[2]/div[1]/button'))).click()

Line four is where I'm stumbling to find the button and click it. I've tried a variety of selectors by XPath and CSS identifiers, but am not quite able to get the Vote button to click. Continue to either receive error that the locator cannot be found or stack traces from Selenium timeouts.

Hoping someone can help identify the proper way of selecting the Vote button on that source page.

CodePudding user response:

You can try the following:

driver = selenium.webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get('https://pnccontests.secondstreetapp.com/ChasChoice_2022/gallery/336759126?group=417500')

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element(By.XPATH, "//*[@id='tncms-block-544689']/p/iframe")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ember2286 button"))).click()

Also, I see you used absolute xpaths. It is not a good practice. Try to use relative xpaths instead of absolute ones. They are easy on maintenance, readability, and execution per se.

  • Related