# coding=utf-8 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import time import os mydriver=webdriver.Firefox() mydriver.get("http://www.126.com/") time.sleep(1) username = 'username' pwd = 'password' mydriver.switch_to.frame(mydriver.find_element_by_id('x-URS-iframe')) # 切入 time.sleep(3) mydriver.find_element_by_xpath("/html/body/div[2]/div[2]/div[2]/form/div/div[1]/div[2]/input").send_keys(username) time.sleep(1) mydriver.find_element_by_xpath("//form[@id='login-form']//div[@class='m-container']//input[@name='password']").send_keys(pwd) time.sleep(2) mydriver.find_element_by_xpath("//form[@id='login-form']//div[@class='m-container']//div[@class='f-cb loginbox']/a").click() time.sleep(5) mydriver.switch_to_default_content() # 切出 nexttitle = mydriver.title print(nexttitle)
1.首先對於iframe結構的網頁 要先用 switch_to.frame 切入 iframe 才能獲得其中的元素。
2.當要獲取 iframe 外部 或者 跳轉了頁面 也要 switch_to_default_content() 切出 iframe 。如果不切出,最后一個print 打印會報 “死對象” 錯誤,原因就是還沒有切出 iframe。