2014-04-25 20 views
5

Sto cercando di accedere a un iframe all'interno di un iframe utilizzando Selenio, Python, e BS4Python Selenio passare in un iframe all'interno di un iframe

from bs4 import BeautifulSoup 
from selenium import webdriver 
import time 
import html5lib 

driver = webdriver.Firefox() 
driver.implicitly_wait(10) 

driver.get('http://myurl.com') 
try: 
    time.sleep(4) 
    iframe = driver.find_elements_by_tag_name('iframe')[0] 
    driver.switch_to_default_content() 

    driver.switch_to_frame(iframe) 
    driver.switch_to_default_content() 
    driver.find_elements_by_tag_name('iframe')[0] 

    output = driver.page_source 

    print output 

finally: 
    driver.quit(); 

All'interno del testo restituito, sembra che vi sia più di due iframe. Come potrei accedere a quelli? Ho tentato nel codice sopra senza successo.

Qualsiasi aiuto è apprezzato.

risposta

14

switch_to_default_content() tornerà all'inizio del documento. Quello che stava succedendo è che sei passato al primo iframe, tornato in cima al documento, poi hai cercato di trovare il secondo iframe. Il selenio non riesce a trovare il secondo iframe, perché è all'interno del primo iframe.

Se si rimuove il secondo switch_to_default_content() si dovrebbe andare bene:

iframe = driver.find_elements_by_tag_name('iframe')[0] 
driver.switch_to_default_content() 

driver.switch_to_frame(iframe) 
driver.find_elements_by_tag_name('iframe')[0]