selenium+python模拟登陆163邮箱

下午学习了一下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)
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值