from selenium import webdriver
import time
import unittest
from selenium.common.exceptions import WebDriverException
import traceback
class javaSciptWebdriver(unittest.TestCase):
# 使用javaScript操作页面元素
def setUp(self):
self.driver = webdriver.Chrome()
self.url = "http://www.baidu.com"
def tearDown(self):
self.driver.quit()
def test_executesScript(self):
self.driver.get(self.url)
# 构造javaScript查找百度首页的搜索输入框的代码字符串
searchInputBoxJs = "document.getElementById('kw').value='光荣之路';"
# 构造javaScript查找百度首页的搜索按钮的代码字符串
searchButtonJs = "document.getElementById('su').click()"
try:
# 通过javaScript代码在百度首页搜索输入框中输入"光荣之路"
self.driver.execute_script(searchInputBoxJs)
time.sleep(2)
# 通过javaScript代码单击百度首页上的搜索按钮
self.driver.execute_script(searchButtonJs)
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())
if __name__ == "__main__":
unittest.main()