selenium12-读取文件 excel

xlrd:读取 excel 文件数据,可读不可写

 

安装 xlrd

pip install xlrd

 

import xlrd  #导入 xlrd

xl = xlrd.open_workbook('test.xls')  #打开 excel

tables = xl.sheets()  #通过索引获取工作表,返回一个列表,列表每个元素是excel中一个表格

table = xl.sheets()[0]  #返回excel中第一个表格

table.nrows  #返回行数

table.ncols  #返回列数

row = table.row_values(0)  #获取第一行内容

col = table.col_values(0)  #获取第一列内容

table.cell(0, 0).value  #返回指定单元格中的值

 

实践练习,读取 excel 中帐号和密码登录 qq 邮箱

 

from selenium import webdriver

import time

from selenium.webdriver.support.ui import WebDriverWait

import xlrd

 

def get_web():

  driver = webdriver.Firefox()

  driver.get('https://mail.qq.com/')

  return driver

def get_login(driver):

  WebDriverWait(driver, 10).until(lambda driver:driver.find_element_by_xpath('/html/body/div/div[1]/a'))

  driver.switch_to.frame('login_frame')

  driver.find_element_by_id('switcher_plogin').click()

def input_login(driver, account, password):

  ele_account = driver.find_element_by_id('u')

  ele_account.clear()

  ele_account.send_keys(account)

  ele_account.send_keys('@qq.com')

  ele_password = driver.find_element_by_id('p')

  ele_password.clear()

  ele_password.send_keys(password)

  driver.find_element_by_xpath('//*[@id="login_button"]').click()

  time.sleep(10)

 

def check_login(driver, account):

  try:

    driver.switch_to.default_content()

    driver.switch_to.frame('mainFrame')

    ele = driver.find_element_by_xpath('/html/body/div[2]/div/ul/li[1]/div[2]/a')

    print('登录账号',account,'成功!')

  except:

    print(account,'登录失败!')

 

if __name__ == "__main__":

  workbooks = xlrd.open_workbook('user.xls')

  workbook = workbooks.sheets()[0]

  num_rows = workbook.nrows

  for i in range(1, num_rows):

    contents = workbook.row_values(i)

    if contents:

      account = contents[0]

      password = contents[1]

      if account and password:

        account = int(account)

        password = str(password)

        print('\n第', i+1, '行,账号', account, '正在登录中……')

        driver = get_web()

        get_login(driver)

        input_login(driver, account, password)

        check_login(driver, account)

        driver.quit()

        time.sleep(3)

      else:

        print('\n第',i+1,'行帐号或密码错误!')

 

输入结果如下:

posted @ 2019-07-31 10:49  星海问道者  阅读(334)  评论(0编辑  收藏  举报