How do you deal with iframes in selenium

iframe The element creates an inline frame that contains another document, that is, the page displayed in the iframe and on the outside do not come from the same HTML file. It's not hard to understand that if you want to edit the page elements in the iframe, you have to switch. If you find that there is no problem with your code but you cannot find the item, then you can check to see if the iframe is inside. 126 mailbox The iframe on the login page worried me for a long, long time. Today I'll take it as an example.

First, publish the 126 mailbox page and the code for the login portion of the iframe


As you can see in the code, the iframe contains a full HTML document with the tag, and that document contains the login form which contains all the elements like username, password and buttons. The basic idea for operating the elements in the iframe is to first go to the frame you want to switch to, then find the element to operate and return to the original page after the operation. Selenium provides switch_to.frame ([Frame-ID]) for operation. The name of the frame, the index (ie the number of frames on the entire web page) or a webElement object can be used in brackets. After all operations in one frame are complete, you can use switch_to.frame () to continue operations in other frames, or you can use switch_to.default_content to return to the outermost HTML page.

Here is an example based on the situation above. Here I first enter the frame that the login is in to get the text of the login button, i.e. login, then jump back to the outermost HTML and print out the text of the help link which is help.

After understanding, the problem that had preoccupied me for a long time was solved very simply.