Selenium中的空iframe尚未填入浏览器(python)

时间:2016-01-10 21:49:53

标签: python selenium iframe

我正在尝试控制Spotify的浏览器播放器。所有控件都放在iframe部分中。

问题: Selenium WebDriver对象中的iframe是EMPTY。然而,iframe在ACTUAL浏览器中填充了正确的内容。

代码示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

import time

username = 'myusername'
base_url = 'https://play.spotify.com/user/spotifydiscover/playlist/76HML2OQXigkyKopqYkeng'

browser = None

def login():
    global browser
    password = input("Password: ")
    browser = webdriver.Firefox()
    browser.get(base_url)

    browser.find_element_by_id('has-account').click()

    browser.find_element_by_id('login-usr').clear()
    browser.find_element_by_id('login-usr').send_keys(username)

    browser.find_element_by_id('login-pass').clear()
    browser.find_element_by_id('login-pass').send_keys(password)
    browser.find_element_by_id('login-pass').submit()

def next_track():
    global browser
    wrapper = browser.find_element_by_id("section-collection")
    print(wrapper.get_attribute('innerHTML').encode('utf-8'))
    iframe = wrapper.find_element_by_tag_name('iframe')
    print(iframe.get_attribute('innerHTML').encode('utf-8'))
    sub = browser.switch_to_frame(iframe)
    sub.find_element_by_id('next').click()

def test():
    login()
    time.sleep(14) # Adjusted until page is 100% fully loaded
    next_track()
    time.sleep(40)

1 个答案:

答案 0 :(得分:2)

问题在于:

iframe = wrapper.find_element_by_tag_name('iframe')

页面上有多个iframes,您对app-player ID感兴趣:

browser.switch_to_frame("app-player")
# now use browser.find_element_* to locate elements inside iframe

另请注意,使用time.sleep会使您的自动化代码严重脆弱且通常比需要的速度慢 - 而是使用Explicit Waits等待页面上满足的特定条件。