自动化测试-20.selenium常用JS代码执行

时间:2023-03-09 00:56:23
自动化测试-20.selenium常用JS代码执行

前言:

  在工作中有些控件定位不到,需要操作,使用JS代码去修改或者操作达到selenium不能做的操作。

1.Web界面的滑动

 1 #coding:utf-8
2 from selenium import webdriver
3 import time
4
5 d = webdriver.Firefox()
6 d.implicitly_wait(10)
7 d.maximize_window()
8 d.get(r'https://www.tmall.com/')
9 time.sleep(10)
10 # 用JS获取HTML元素焦点,滚动条就自动滑动到焦点所在位置
11 # .mui-mbar-tab.mui-mbar-tab-cart.mui-mbar-tab-cart-nologin>div:nth-child(2)
12 # 查找class属性值为"mui-mbar-tab mui-mbar-tab-cart mui-mbar-tab-cart-nologin"的元素下的第二个div元素
13 ele = d.find_element_by_css_selector('.mui-mbar-tab.mui-mbar-tab-cart.mui-mbar-tab-cart-nologin>div:nth-child(2)')
14 #print ele.text
15 # 获取一个焦点
16 js = "arguments[0].scrollIntoView();"
17 # 获取ele元素所在的位置焦点,滚动条会自动的滑动到获取的焦点位置
18 d.execute_script(js,ele)

2.js来拖动滚动条滚动到具体位置

 js_="window.scrollTo(400,700);"
driver.execute_script(js_)

3.针对js  非div 元素的 alert 弹出事件 可以用:

 from selenium.webdriver import ActionChains
alert = driver.switch_to_alert()
#模拟键盘Enter 键
ActionChains(driver).send_keys(Keys.ENTER).perform()

4.用来选择日期控件,输入框

 js="$('#SystemDate').val('2017-07-21');"
driver.execute_script(js

5.Python执行js删除HTML元素的属性值


'''
1. 删除属性值:document.getElementById('promote_start_date').removeAttribute('readonly')
2. 添加/修改属性值:document.getElementById("p1").readonly=false
JS定位元素的方法:document.getElementById/getElementByName/getElementByClassName/getElementByTagName
''' js="document.getElementById('promote_start_date').removeAttribute('readonly')"
driver.execute_script(js)
driver.find_element_by_id('promote_start_date').clear()
# 填写促销日期(promote_start_date)为日期控件的id
driver.find_element_by_id('promote_start_date').send_keys('1996-05-25')

6.工作中持续更新使用到的JS脚本