selenium+python模擬登陸163郵箱
阿新 • • 發佈:2019-02-13
下午學習了一下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)