1、使用JavaScript操作页面元素:
目的:在webdriver脚本代码中执行JavaScript代码,来实现对页面元素的操作,主要用于解决在某些情况下页面原色的Click方法无法生效问题;
# coding = utf-8
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import unittest
import traceback
import time
class TestDemo(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="D:\\software\\chromedriver")
def test_executeScript(self):
self.driver.get("http://www.baidu.com")
# 构造JavaScript查找百度首页的搜搜输入框的代码字符串
searchInputBoxJS = "document.getElementById('kw').value='光荣之路'"
searchButtonBoxJS = "document.getElementById('su').click()"
try:
self.driver.execute_script(searchInputBoxJS)
time.sleep(2)
self.driver.execute_script(searchButtonBoxJS)
time.sleep(2)
self.assertTrue(u"百度百科" in self.driver.page_source)
except WebDriverException:
print(u"在页面中没有找到要操作的页面元素", traceback.print_exc())
except AssertionError:
print(u"页面不存在关键子串")
except Exception:
print(traceback.print_exc())
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
2、操作Web页面滚动条:
目的:滑动页面的滚动条到页面最下面、滑动页面滚动条到页面某个元素、滑动页面的滚动条向下移动某个数量的像素;
# coding = utf-8 from selenium import webdriver import unittest import traceback import time class TestDemo(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path="D:\\software\\chromedriver") def test_scroll(self): try: self.driver.get("http:www.seleniumhq.org/") # 使用JavaScript的scrollTo函数和document.body.scrollHeight参数将页面的滚动条滑动到页面的最下方 self.driver.execute_script("window.scrollTo(100,document.body.scrollHeight);") time.sleep(3) # 使用JavaScript的scrollIntoView函数将被遮挡的元素滚动到屏幕上,scrollIntoView(true)表示将元素滚动到屏幕中间, # false表示将元素滚动到屏幕底部 self.driver.execute_script("document.getElementById('choice').scrollIntoView(true);") time.sleep(3) # 使用JavaScript的scrollBy方法使用0和400横纵坐标参数 self.driver.execute_script("window.scrollBy(0,400);") time.sleep(3) except Exception: print(traceback.print_exc()) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
3、