Python+selenium+chromedriver的自动化测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanglong_web/article/details/79203372

  更一篇简单的吧
  因为朋友所在的公司想做一些节省人力财力的事,对于某个简单网站的操作想变为全自动的形式,其实开始我是比较蒙的,既然决定试试,就开始在网上各种搜资源,开始接触了按键精灵,个人不是很喜欢。后来转为做nodejs的脚本,自动调后台接口,无奈人家接口不给直接调,还是要通过操作他们的系统去调,后来萌生的想法是自动化测试,既不需要人去操作也不会直接暴露他们的接口。
  研究了一段时间Python,决定用python+selenium去写,selenium可以很方便的去得到网页的dom元素,直接上代码吧danmu.py

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import org.openqa.selenium.JavascriptExecutor;
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get('') # 登录地址,就不透露了~

pageWait = WebDriverWait(driver, 10)
userName = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='text']"))).send_keys(u'fengjiale')
passWord = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='password']"))).send_keys(u'123')
loginBtn = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()
userSide = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#appMenuNav li:nth-of-type(1)"))).click()
liveRoom = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[ng-model='roomUrl']")))

liveRoom.send_keys(u'https://www.zhanqi.tv/baiyou')

nameType = Select(pageWait.until(EC.element_to_be_clickable((By.TAG_NAME, "select"))))

# 判断选择第几个以便选择人数
nameType.select_by_index(0)
sendTimes = pageWait.until(EC.element_to_be_clickable((By.NAME, "times"))).send_keys(u'1')
sendCount = pageWait.until(EC.element_to_be_clickable((By.NAME, "intvl"))).send_keys(u'0')
# 遍历发送
danmuCotent = pageWait.until(EC.element_to_be_clickable((By.NAME, "text"))).send_keys(u'666')

sendBtn = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

  需要注意的是下载chromedriver的时候一定注意chrome的版本和chromedriver的版本,它们两个有对应的关系,关于具体的对应可以查一下,还有就是关于selenium的使用也有详细的文档,大家最经常遇到的问题就是通过selenium获取不到dom元素,一种是dom元素是通过js动态生成的,这个需要捕捉到network里面的请求,还有一种可能就是页面还没有加载完成就去通过selenium去获取元素,这个时候我们就需要异步的去等待页面加载

pageWait = WebDriverWait(driver, 10)

  上面的意思就是在10秒内找元素找不到的话不会报错,一般网站10秒内肯定是加载完了
  直接python danmu.py 就会自动帮我们去做一些登录,填数据,发送的操作了,如果需要重复发送,那在如下代码加入循环就好

# 遍历发送
danmuCotent = pageWait.until(EC.element_to_be_clickable((By.NAME, "text"))).send_keys(u'666')

sendBtn = pageWait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

  整个过程还是比较简单的

猜你喜欢

转载自blog.csdn.net/zhanglong_web/article/details/79203372