根据关键字启动一个浏览器,一般是这样的写法:
from selenium import webdriver
def browser(driver_type):
if driver_type=='chrome':
driver = webdriver.Chrome()
return driver
elif driver_type=='firefox':
driver = webdriver.Firefox()
return driver
elif driver_type=='ie':
driver = webdriver.Ie()
return driver
driver_type='chrome'
driver=browser('chrome')
print(driver)
还有种写法:
driver_type='chrome'
driver_dict={
'chrome':webdriver.Chrome,
'firefox':webdriver.Firefox,
'ie':webdriver.Ie
}
driver=driver_dict[driver_type]
下面要说的是另一种写法,在python中有一个函数叫getattr, 是获取对象属性或方法的函数。
基于此,可以利用关键字直接启动对应的浏览器,代码如下:
driver_type='chrome'
driver =getattr(webdriver,driver_type.capitalize())
print(driver)