简体   繁体   中英

How can I click on content within an iframe?

I am trying to use Selenium to click buttons on a web page. I use this code:

driver.find_element(By.Xpath, '//*[@id="payments"]').click()

Normally this works, but it does not seem to be able to click the button shown in this HTML:

<iframe src="/ProviderPortal" id="main-iframe" frameborder="0" style="min-height: 600px; height: 600px;">
<a href="/ProviderPortal/Payment" id="payments">Payments</a>
</iframe>

When I run the code, nothing happens - it does not proceed to the next URL. The other buttons, that were successfully clicked, were not within an iframe. Is this the reason for the problem? How can I make it click successfully?

In order to access web element(s) inside an iframe you need to switch to the iframe first. Like the following:

driver.switch_to.frame(driver.find_element_by_id('main-iframe'))
driver.find_element(By.Xpath, '//*[@id="payments"]').click()

Once you finished working inside an iframe you will have to switch out from the iframe to the default content with

driver.switch_to.default_content()

First you need to switch to that iframe by: drive.switch_to.frame(1)

Then swicth back to main content:

driver.switch_to.default_content()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM