下午学习了一下selenium写自动化脚本,原本书上的教程是模拟登陆126邮箱,所以我想做一个模拟登陆163邮箱,没想到里面还有很多坑。
1、163邮箱的账号密码区域的input标签的id是自动生成的,每次都不能用,所以不能用于定位标签
2、登陆处是一个iframe,需要程序中切换一下:drive.switch_to.frame(),不然会找不到标签
3、加载这个iframe需要一定时间,所以需要设一个等待直至获取到标签:
element=WebDriverWait(drive,30,0.5).until(EC.presence_of_element_located((By.XPATH,”//*[@id=’x-URS-iframe’]”)))
由于id不可用,所以找两个element的时候就从有固定不变id的标签开始找,然后自己写xpath。。。
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
drive=webdriver.Chrome()
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
drive.get("http://mail.163.com/")
element=WebDriverWait(drive,30,0.5).until(EC.presence_of_element_located((By.XPATH,"//*[@id='x-URS-iframe']"))) #等待直到出现填写账号密码iframe
drive.switch_to.frame("x-URS-iframe") #切换标签
inputText=drive.find_element(By.XPATH,"//*[@id='account-box']//div[2]//input") # 定位到账号框
inputText.send_keys("你的邮箱")
password=drive.find_element(By.XPATH,"//*[@id='login-form']//div//div[3]//div[2]//input[2]") //定位到密码框
password.send_keys("你的密码")
password.send_keys(Keys.ENTER) #模拟回车键
time.sleep(5)
drive.quit()
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
class Login():
def __init__(self):
self.driver=webdriver.Chrome()
self.driver.get("http://mail.163.com/")
def login(self,username,pw):
element=WebDriverWait(self.driver,30,0.5).until(EC.presence_of_element_located((By.XPATH,"//*[@id='x-URS-iframe']")))
self.driver.switch_to.frame("x-URS-iframe")
inputText=self.driver.find_element(By.XPATH,"//*[@id='account-box']//div[2]//input")
inputText.send_keys(username)
password=self.driver.find_element(By.XPATH,"//*[@id='login-form']//div//div[3]//div[2]//input[2]")
password.send_keys(pw)
password.send_keys(Keys.ENTER)
def logout(self,driver):
self.driver.find_element_by_link_text('退出').click()
time.sleep(5)
外部调用:
# -*- coding: utf-8 -*-
from selenium import webdriver
from simulate163 import Login
username="你的邮箱名"
password="你的密码"
Login().login(username,password)