代码:
#coding=utf-8
from selenium import webdriver
import time
import requests
import json
from selenium.webdriver.support import expected_conditions as EC
##############5-4:封装打开页面方法及判断页面是否正确_start################
#类使用
class SeleniumDriver:
def __init__(self,browser):
self.driver = self.open_browser(browser)
def open_browser(self, browser):
try:
if browser == 'Edge':
driver = webdriver.Edge()
elif browser == 'ie':
driver = webdriver.Ie()
elif browser == 'chrome':
driver = webdriver.Chrome()
else:
#browser == 'firefox':
driver =webdriver.Firefox()
return driver
except:
print('打开浏览器失败')
return None
def get_url(self,url):
if self.driver != None:
time.sleep(1)
self.driver.maximize_window()
if 'http' in url:
self.driver.get(url)
else:
print("你的URL有问题")
else:
print("case失败")
def handle_windos(self, *args):
value = len(args)
if value == 1:
if args[0] == 'max':
self.driver.maximize_window()
elif args[0] == 'min':
self.driver.minimize_window()
elif args[0] == 'back':
self.driver.back()
elif args[0] == 'forward':
self.driver.forward()
else:
self.driver.refresh()
elif value == 2:
self.driver.set_window_size(args[0],args[1])
else:
print("参数有误")
self.driver.quit()
def assert_title(self, title_name=None):
"""
方法目的:判断title是否正确
"""
if title_name != None:
get_title = EC.title_contains(title_name)
return get_title(self.driver)
def open_url_is_true(self, url, title_name=None):
"""
理解点:
1.实装该方法时,需要和assert_title结合
2.为什么不把assert_title方法写在该方法里面?
考虑到有可能其他地方会单独调到assert_title,就单独做一个assert_title方法。
3.综上1.和2.所述,需要在该方法里面调用assert_tilte方法。
方法目的:通过title判断页面是否正确
"""
self.get_url(url)
return self.assert_title(title_name)
selenium_driver = SeleniumDriver('chrome')
# selenium_driver.handle_windos('max')
print(SeleniumDriver.open_url_is_true("https://www.imooc.com/", "程序员"))
##############5-4:封装打开页面方法及判断页面是否正确_end################
结果:
PS E:\30.Study\30.自动化测试\99.零基础入门 Python Web 自动化测试\10.seleniumCodePractice> & "C:/Program Files/Python38/python.exe" "e:/30.Study/30.自动化测试/99.零基础
入门 Python Web 自动化测试/10.seleniumCodePractice/202006/open_browser_5-4.py"
DevTools listening on ws://127.0.0.1:51101/devtools/browser/b1c991e3-d0a4-4233-a0c2-f5a1d6a178d8
Traceback (most recent call last):
File "e:/30.Study/30.自动化测试/99.零基础入门 Python Web 自动化测试/10.seleniumCodePractice/202006/open_browser_5-4.py", line 83, in <module>
print(SeleniumDriver.open_url_is_true("https://www.imooc.com/", "程序员"))
File "e:/30.Study/30.自动化测试/99.零基础入门 Python Web 自动化测试/10.seleniumCodePractice/202006/open_browser_5-4.py", line 78, in open_url_is_true
self.get_url(url)
AttributeError: 'str' object has no attribute 'get_url'
PS E:\30.Study\30.自动化测试\99.零基础入门 Python Web 自动化测试\10.seleniumCodePractice>
原因分析:
日志里提示在第83行调用有问题,仔细查看,原来是实例selenium_driver之后,想要通过selenium_driver 来调取类方法open_url_is_true,但是调取名字误写成了类名SeleniumDriver。
对应方法:
print(SeleniumDriver.open_url_is_true("https://www.imooc.com/", "程序员"))
==>
print(selenium_driver.open_url_is_true("https://www.imooc.com/", "程序员"))
思考:
为什么通过类名不能调用自己类里的方法?