如何点击iframe中的元素?

时间:2017-12-07 15:44:08

标签: python selenium iframe

在网站https://www.google.com/recaptcha/api2/demo我尝试点击iframe(recaptcha),然后点击带有耳机图标的按钮。但是我不能。怎么做?错误在哪里?

driver.get(RECAPTCHA_PAGE_URL)
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
iframes = driver.find_elements_by_tag_name("iframe")
driver.switch_to_frame(iframes[0])
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//div[@class="recaptcha-checkbox-checkmark" and @role="presentation"]').click()
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//button[@id="recaptcha-audio-button"]').click()
time.sleep(random.uniform(LONG_MIN_RAND, LONG_MAX_RAND)) 

MIN_RAND,MAX_RAND,LONG_MIN_RAND,LONG_MAX_RAND是nums。 错误:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <iframe name="etxg0ejyszkb" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=r20171129143447&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-#etxg0ejyszkb"> stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

1 个答案:

答案 0 :(得分:0)

您需要先切换到iframe。像这样的东西

    driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
相关问题