selenium自动化测试过程中,有时候会要使用js操作页面员,我们需要掌握的js几种用法如下:
一、js定位元素
- 1、document.getElementById():通过元素的id属性去定位元素
- 2、document.getElementByClassName():通过元素的classname属性去定位元素,可能会获得多个值
二、js修改元素的属性
- 1、定位元素
- 2、元素.属性名 = 属性值
三、js修改元素的内容
- 1、定位元素
- 2、元素.innerHTML = ‘值’
注意点:innerHTML可以传html元素,innerText传进去的全部当成文本
四、js打开新的页面窗口
window.open(url)
五、js滑动页面
- 1、相对于当前位置进行滑动:window.scrollBy(x,y)
x:横向滑动的像素值
y:纵向滑动的像素值 - 2、滑动到页面指定位置:window.scrollTo(x,y)
x:横向滑动的像素值
y:纵向滑动的像素值
selenium操作中对页面滚动条操作有4种操作:
def scroll(self ,loc,type):
ele = self.locator(loc)
if type == '顶部':
self.driver.execute_script("window.scrollTo(document.body.scrollHeight,0)")
# 滚动条到页面顶部
elif type == '底部':
self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
# 滚动条到页面底部
elif type == '窗口顶部':
self.driver.execute_script("arguments[0].scrollIntoView();",ele)
# 滚动条到当前窗口顶部
else:
self.driver.execute_script("arguments[0].scrollIntoView(false);", ele)
# 滚动条到当前窗口底部