以下用百度搜索举例,模仿类调用实例的方法来写脚本。一个.py文件可以说是一个模块,一个模块中,可以定义多个class,模块下也可以直接定义函数。
import os, time
from seleniumimport webdriver
class BaiduSearch(object):
file_path = os.path.dirname(os.path.abspath('../framework')) +"/tools/chromedriver.exe"
driver = webdriver.Chrome(file_path)
driver.maximize_window()
def open_baidu(self):
self.driver.get("https://www.baidu.com")
time.sleep(2)
def test_search(self):
self.driver.find_element_by_id('kw').send_keys("selenium")
self.driver.find_element_by_xpath(" // *[ @ id = 'su']").click()
time.sleep(2)
print(self.driver.title)
try:
assert 'selenium' in self.driver.title
print('test pass.')
except Exception as e:
print('test fail!', format(e))
self.driver.quit()
baidu = BaiduSearch()
baidu.open_baidu()
baidu.test_search()