我正在尝试单击iframe弹出窗口,但无法使其聚焦。
这是弹出窗口和我要单击的按钮:
这是我到目前为止的代码:
patsearch = driver.find_element_by_xpath('// * [@ id =“ command_idSearchButton”] / nobr')。click()
time.sleep(5)
iframe = driver.find_element_by_xpath('//*[@id="iframe_52"]')
driver.switch_to.frame(iframe)
mrn = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_15"]'))).send_keys(mrnum)
time.sleep(1)
ln = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_18"]'))).send_keys(last_name)
time.sleep(1)
fn = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_19"]'))).send_keys(first_name)
time.sleep(1)
search = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_66"]'))).click()
#try: click patient if one exists / try warning pop alert / exception warning / exception nopatient exists wrtie to file
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="idHTMLResult"]/table/tbody/tr[2]/td[4]/a'))).click()
try:
print('trying to switch..')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "frame_116")))
print('switched')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_8"]')))
driver.switch_to_default_content()
except TimeoutException:
print('didnt switch...')
这是HTML:
解决方案:
iframe = driver.find_element_by_xpath('//*[@id="iframe_52"]')
driver.switch_to.frame(iframe)
#do something
#try: click account if one exists / try warning pop alert / exception warning / exception no account exists write to file
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="idHTMLResult"]/table/tbody/tr[2]/td[4]/a'))).click()
try:
driver.switch_to_default_content()
print('trying to switch..')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "frame_116")))
print('switched')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="control_8"]'))).click()
driver.switch_to_default_content()
except:
driver.switch_to.frame(iframe)
答案 0 :(得分:2)
使用显式等待来定位iframe
并切换到它:
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
ui.WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "frame_116")))
PS:此代码将替换以下行:
warning = driver.find_element_by_xpath('//*[@id="frame_116"]')
driver.switch_to_frame(warning)
希望对您有帮助!
答案 1 :(得分:0)
能否请您尝试一下并检查它是否有效。可以代替类名尝试使用ID来检查它是否有效。
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CLASS_NAME, "modalGroupIframe")))
driver.find_element_by_xpath('//div[@class="modalGroupIframe"]')