LoginSignup
8
6

More than 3 years have passed since last update.

Seleniumでページ内のiframeを操作できない

Last updated at Posted at 2020-06-30

問題

Selenium/BeautifulSoupを使ってページ内のiframeの内容を取得しようとしたが、できない。

BeautifulSoupでHTMLを全取得すると以下のような結果になる。

HTMLを取得するコード
BeautifulSoup(driver.page_source, 'html.parser')
取得結果
<html>
    <head>
        <!-- head -->
    </head>
    <body>
        <!-- body -->
        <iframe id="iframe" 
                scrolling="yes"
                src="https://example.com/iframe"
                src_data="https://example.com/iframe">
        </iframe>
    </body>
</html>

やりたいこと

iframeのなかを見たい、操作したい。

解決方法

以下のコードで、driverがiframeにフォーカスする。

iframe = driver.find_element_by_id('#iframe')
driver.switch_to.frame(iframe)
HTMLを取得するコード
BeautifulSoup(driver.page_source, 'html.parser')

でHTMLがiframeになっていることを確認してください。

参考

追記

元のウィンドウに戻る際は以下のコードで戻ります。

driver.switch_to.default_content()
8
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6