163邮箱登陆为例:
在最近的python3中switch_to_frame()会中间有一道横杆,更改为switch_to.frame()即可
from selenium import webdriver
import time
def login(self):
driver = webdriver.Chrome()
time.sleep(3)
driver.get("https://mail.163.com/")
driver.maximize_window()
time.sleep(5)
title = driver.title # 读取网站标题
print(title)
xpath=driver.find_element_by_xpath('//*[@id="loginDiv"]/iframe')
driver.switch_to.frame(xpath) # 跳入frame中
driver.find_element_by_xpath("//*[@id='login-form']/div/div/div[2]/input").send_keys(self.name) # 输入账号
driver.find_element_by_xpath("//*[@id='login-form']/div/div[3]/div[2]/input[2]").send_keys(self.password) # 输入密码
driver.find_element_by_xpath("//*[@id='login-form']/div/div[8]/a").click() # 登录
time.sleep(5)
driver.switch_to.default_content() # 退出frame到主层级
# print(driver.window_handles)#获取庄口语句柄
try:
shouye = driver.find_element_by_xpath("//*[@id='spnUid']").text # 断言获取邮箱地址值
print(shouye)
except Exception as e:
print("登录失败")