Python selenium.webdriver 模块,Ie() 实例源码
我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用selenium.webdriver.Ie()。
def create_selenium_driver(browser='chrome'):
# set default browser string based on env (if available)
env_browser = os.environ.get('TOASTER_TESTS_BROWSER')
if env_browser:
browser = env_browser
if browser == 'chrome':
return webdriver.Chrome(
service_args=["--verbose", "--log-path=selenium.log"]
)
elif browser == 'firefox':
return webdriver.Firefox()
elif browser == 'marionette':
capabilities = DesiredCapabilities.FIREFOX
capabilities['marionette'] = True
return webdriver.Firefox(capabilities=capabilities)
elif browser == 'ie':
return webdriver.Ie()
elif browser == 'phantomjs':
return webdriver.PhantomJS()
else:
msg = 'Selenium driver for browser %s is not available' % browser
raise RuntimeError(msg)
def get_driver(self, task):
"""Get the webdriver instance"""
from selenium import webdriver
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'support', 'IE')
reg_file = os.path.join(path, 'keys.reg')
if os.path.isfile(reg_file):
run_elevated('reg', 'IMPORT "{0}"'.format(reg_file))
if platform.machine().endswith('64'):
path = os.path.join(path, 'amd64', 'IEDriverServer.exe')
else:
path = os.path.join(path, 'x86', 'IEDriverServer.exe')
capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER.copy()
capabilities['ie.enableFullPageScreenshot'] = False
if not task['cached']:
capabilities['ie.ensureCleanSession'] = True
driver = webdriver.Ie(executable_path=path, capabilities=capabilities)
return driver
def __init__(self, driver, browser='chrome'):
"""
initialize selenium webdriver, use chrome as default webdriver
"""
if not driver:
if browser == "firefox" or browser == "ff":
driver = webdriver.Firefox()
elif browser == "chrome":
driver = webdriver.Chrome()
elif browser == "internet explorer" or browser == "ie":
driver = webdriver.Ie()
elif browser == "opera":
driver = webdriver.Opera()
elif browser == "phantomjs":
driver = webdriver.PhantomJS()
try:
self.driver = driver
self.wait = WebDriverWait(self.driver, 20)
except Exception:
raise NameError("Not found %s browser,You can enter 'ie', 'ff' or 'chrome'." % browser)
else:
self.driver = driver
self.wait = WebDriverWait(self.driver, 20)
def __init__(self, base_url=None, pagetitle=None):
self.base_url = base_url
self.pagetitle = pagetitle
# self.driver = webdriver.Firefox()
# self.driver.implicitly_wait(30)
# self.driver = driver
"""
???????????
# self.browser = "Firefox" #???????
# if Action.driver == None:
# if self.browser.upper() == 'IE': Action.driver = webdriver.Ie()
# elif self.browser.upper() == 'CHROME': Action.driver = webdriver.Chrome()
# elif self.browser.upper() == 'FIREFOX': Action.driver = webdriver.Firefox()
# elif self.browser.upper() == 'SAFARI': Action.driver = webdriver.Safari()
# else: Action.driver = webdriver.Ie()
# Action.driver.maximize_window()
# #pass
# #print u"?????????!"
# self.driver = Action.driver
self.verificationErrors = []
"""
#?????????????????
def flush(browser, n):
ua = DesiredCapabilities().IPHONE
for i in range(n):
if browser.lower() == 'firefox':
driver = webdriver.Firefox()
elif browser.lower() == 'chrome':
options = webdriver.ChromeOptions()
options.add_argument('--disable-extensions')
driver = webdriver.Chrome(executable_path=driver_path + 'chromedriver.exe', chrome_options=options)
elif browser.lower() == 'ie':
driver = webdriver.Ie(executable_path=driver_path + 'IEDriverServer.exe')
elif browser.lower() == 'phantomjs':
killphantomjs()
driver = webdriver.PhantomJS(executable_path=driver_path + 'phantomjs.exe', desired_capabilities=ua)
driver.get('http://m.baidu.com')
driver.find_element_by_id('index-kw').send_keys(random.choice(KEYWORDS), Keys.ENTER)
clk(driver, url='csdn')
sleep(1)
print driver.find_element_by_class_name('article_t').text,
print driver.find_element_by_xpath('//p[@class="date"]/i[2]').text
driver.close()
def open_browser(browser='firefox', profile=None, *args, **kwargs):
"""?????????????firefox,chrome,IE,????????
????????????????????????"""
if browser.lower() == 'firefox':
if profile is None:
driver = webdriver.Firefox()
else:
driver = webdriver.Firefox(profile)
elif browser.lower() == 'chrome':
driver = webdriver.Chrome(TOOLS_PATH + 'browsertools\\chromedriver.exe')
elif browser.lower() == 'ie':
driver = webdriver.Ie(TOOLS_PATH + 'browsertools\\IEDriverServer.exe')
else:
log(u'open browser {0}'.format(browser), 'failed : UnsupportBrowser')
raise UnsupportBrowser(msg='?????????')
driver.maximize_window()
driver.implicitly_wait(30)
log(u'open browser {0}'.format(browser), 'success.', 'info')
return driver
def __init__(self, browser='firefox'):
"""
Run class initialization method, the default is proper
to drive the Firefox browser,. Of course, you can also
pass parameter for other browser, such as Chrome browser for the "Chrome",
the Internet Explorer browser for "internet explorer" or "ie".
"""
if browser == "firefox" :
driver = webdriver.Firefox()
elif browser == "chrome":
driver = webdriver.Chrome()
elif browser == "ie" :
driver = webdriver.Ie()
elif browser == "phantomjs":
driver = webdriver.PhantomJS()
try:
self.driver = driver
except Exception:
raise NameError("Not found this browser,You can enter 'firefox', 'chrome', 'ie' or 'phantomjs'.")
def start(self):
try:
if self.browser == "Firefox":
driver = webdriver.Firefox()
driver.get(self.url)
return driver
elif self.browser == "IE":
driver = webdriver.Ie()
driver.get(self.url)
return driver
elif self.browser == "HtmlUnit":
# ????? selenium-server
driver = webdriver.Remote("http://127.0.0.1:4444/wd/hub/",
desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS)
return driver
elif self.browser =="Chrome":
driver = webdriver.Chrome()
driver.get(self.url)
return driver
else: # ??
#
driver = webdriver.Remote(command_executor='http://192.168.50.162:1111/wd/hub',
desired_capabilities=webdriver.DesiredCapabilities.CHROME)
driver.get(self.url)
return driver
except:
print(str(sys.exc_info()))
def setup_browser(self, *browser_path):
self.browser = eval(self.parser.get('toaster_test_' + self.target_suite, 'test_browser'))
print(self.browser)
if self.browser == "firefox":
driver = webdriver.Firefox()
elif self.browser == "chrome":
driver = webdriver.Chrome()
elif self.browser == "ie":
driver = webdriver.Ie()
else:
driver = None
print("unrecognized browser type, please check")
self.driver = driver
self.driver.implicitly_wait(30)
return self.driver
def openBrower():
print("?????...")
# driver = webdriver.Firefox()
# driver = webdriver.Ie()
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
driver = webdriver.Chrome(chrome_options=options)
# driver = webdriver.Chrome()
return driver
def openBrower():
print(u"?????...")
# driver = webdriver.Firefox()
# driver = webdriver.Ie()
driver = webdriver.Chrome()
return driver
def get_cookie():
loginurl = 'https://malwr.com/account/login/'
driver = webdriver.Ie()
driver.get(loginurl)
WebDriverWait(driver,3).until(lambda x:x.find_element_by_link_text('Logout'))
cookies = driver.get_cookies()
driver.close()
return cookies
def start_driver_session(context: Context, session_name: str):
desired_capabilities = context.desired_capabilities
desired_capabilities["name"] = session_name
if CONFIG["hub_url"]:
context.driver = webdriver.Remote(
desired_capabilities=desired_capabilities,
command_executor=CONFIG["hub_url"])
else:
browser_name = CONFIG["environments"][0]["browser"]
drivers = {
"chrome": webdriver.Chrome,
"edge": webdriver.Edge,
"firefox": webdriver.Firefox,
"ie": webdriver.Ie,
"phantomjs": webdriver.PhantomJS,
"safari": webdriver.Safari,
}
# start the browser
context.driver = drivers[browser_name.lower()]()
context.driver.set_page_load_timeout(time_to_wait=27)
try:
context.driver.maximize_window()
logging.debug("Maximized the window.")
except WebDriverException:
logging.debug("Failed to maximize the window.")
try:
context.driver.set_window_size(1600, 1200)
logging.warning("Set window size to 1600x1200")
except WebDriverException:
logging.warning("Failed to set window size, will continue as is")
logging.debug("Browser Capabilities: %s", context.driver.capabilities)
def webdriver(self):
"""Return the webdriver instance, instantiate it if necessary."""
if self._webdriver is None:
short_arg_classes = (webdriver.Firefox, webdriver.Ie)
if issubclass(self._browser, short_arg_classes):
cap_attr = 'capabilities'
else:
cap_attr = 'desired_capabilities'
options = self._options
options[cap_attr] = self._desired_capabilities
self._webdriver = self._browser(**options)
self._webdriver.set_window_size(settings.DRIVER_WINDOW_WIDTH, settings.DRIVER_WINDOW_HEIGHT)
self._webdriver.set_page_load_timeout(self.crawler.settings.get('DOMAIN_TIMEOUT', 30))
self.crawler.signals.connect(self._cleanup, signal=engine_stopped)
return self._webdriver
def start_requests(self):
search_fields = [u'']
#search_fields = self.query
root_url = 'https://www.lagou.com'
urls = []
for field in search_fields:
driver = webdriver.Ie('C:\Program Files\Internet Explorer\IEDriverServer.exe') # open browser
driver.get(root_url) # open root url
time.sleep(1) # waiting for closing dialog
driver.find_element_by_id('search_input').send_keys('%s' % field)
driver.find_element_by_id('search_button').click()
time.sleep(2) # waiting for redirection
i = 0
flag = True#if there is no page column,then skip the search
try:
class_name = driver.find_element_by_xpath('//span[@action="next"]').get_attribute('class')
print class_name
except Exception:
flag = False
print "position is too sparse!"
##### to crawl 16 pages#####
while flag and class_name == "pager_next " and i < 16:#there is a space after pager_next~
time.sleep(1)
position_links = driver.find_elements_by_class_name('position_link')
for position_link in position_links:
job_url = position_link.get_attribute('href')
print('adding new seed url: %s' % job_url)
urls.append(job_url)
for url in urls:
yield Request(url=url, callback=self.parse_page)
i += 1
print "parsing page: ",i
driver.close()
driver.find_element_by_class_name('pager_next ').click()#go to the next page
class_name = driver.find_element_by_xpath('//span[@action="next"]').get_attribute('class')
def _make_ie(self , remote , desired_capabilities , profile_dir):
return self._generic_make_browser(webdriver.Ie,
webdriver.DesiredCapabilities.INTERNETEXPLORER, remote, desired_capabilities)
def create_driver():
try:
web = webdriver.Firefox()
print " [*] Opening Mozila FireFox..."
return web
except:
try:
web = webdriver.Chrome()
print " [*] We got some errors running Firefox, Opening Google Chrome instead..."
return web
except:
try:
web = webdriver.Opera()
print " [*] We got some errors running Chrome, Opening Opera instead..."
return web
except:
try:
web = webdriver.Edge()
print " [*] We got some errors running Opera, Opening Edge instead..."
return web
except:
try:
web = webdriver.Ie()
print " [*] We got some errors running Edge, Opening Internet Explorer instead..."
return web
except:
print " Error: \n Can not call any WebBrowsers\n Check your Installed Browsers!"
exit()
#Stolen from stackoverflow :D
def run_local(self,os_name,os_version,browser,browser_version):
"Return the local driver"
local_driver = None
if browser.lower() == "ff" or browser.lower() == 'firefox':
local_driver = webdriver.Firefox()
elif browser.lower() == "ie":
local_driver = webdriver.Ie()
elif browser.lower() == "chrome":
local_driver = webdriver.Chrome()
elif browser.lower() == "opera":
local_driver = webdriver.Opera()
elif browser.lower() == "safari":
local_driver = webdriver.Safari()
return local_driver
def ie():
dc = webdriver.DesiredCapabilities.INTERNETEXPLORER
dc["requireWindowFocus"] = True
dc["ignoreProtectedModeSettings"] = True
dc["javascriptEnabled"] = True
return webdriver.Ie(capabilities=dc)
def test_ie_manager_with_selenium(version, use_cache):
delete_old_install()
if use_cache:
IEDriverManager(version).install()
driver_path = IEDriverManager(version).install()
dr = webdriver.Ie(driver_path)
dr.quit()
def mode_local(self):
"""Open new brower on local mode"""
browser_name = self.bot_config.config['browser']
if browser_name == "chrome":
self.curr_caps = DesiredCapabilities.CHROME.copy()
self.curr_driver = WebDriver.Chrome(
executable_path=self.curr_driver_path,
desired_capabilities=self.curr_caps
)
elif browser_name == "firefox":
self.curr_caps = DesiredCapabilities.FIREFOX.copy()
self.curr_driver = WebDriver.Firefox(
executable_path=self.curr_driver_path,
capabilities=self.curr_caps
)
elif browser_name == "iexplorer":
self.curr_caps = DesiredCapabilities.INTERNETEXPLORER.copy()
self.curr_driver = WebDriver.Ie(
executable_path=self.curr_driver_path,
capabilities=self.curr_caps
)
elif browser_name == "edge":
self.curr_caps = DesiredCapabilities.EDGE.copy()
self.curr_driver = WebDriver.Edge(
executable_path=self.curr_driver_path,
capabilities=self.curr_caps
)
elif browser_name == "phantomjs":
self.curr_caps = DesiredCapabilities.PHANTOMJS.copy()
self.curr_driver = WebDriver.PhantomJS(
executable_path=self.curr_driver_path,
desired_capabilities=self.curr_caps
)
elif browser_name == "opera":
self.curr_caps = DesiredCapabilities.OPERA.copy()
self.curr_driver = WebDriver.Opera(
executable_path=self.curr_driver_path,
desired_capabilities=self.curr_caps
)
else:
raise CoreException(
message=("config file error, SECTION=bot, KEY=browser isn't "
"valid value: {}".format(browser_name)),
log=self.log
)
def create_webdriver(self, driver_name, alias=None, kwargs={}, **init_kwargs):
"""Creates an instance of a WebDriver.
Like `Open Browser`, but allows passing arguments to a WebDriver's
__init__. _Open Browser_ is preferred over _Create Webdriver_ when
feasible.
Returns the index of this browser instance which can be used later to
switch back to it. Index starts from 1 and is reset back to it when
`Close All Browsers` keyword is used. See `Switch Browser` for
example.
`driver_name` must be the exact name of a WebDriver in
_selenium.webdriver_ to use. WebDriver names include: Firefox, Chrome,
Ie, Opera, Safari, PhantomJS, and Remote.
Use keyword arguments to specify the arguments you want to pass to
the WebDriver's __init__. The values of the arguments are not
processed in any way before being passed on. For Robot Framework
< 2.8, which does not support keyword arguments, create a keyword
dictionary and pass it in as argument `kwargs`. See the
[http://selenium.googlecode.com/git/docs/api/py/api.html|Selenium API Documentation]
for information about argument names and appropriate argument values.
Examples:
| # use proxy for Firefox | | | |
| ${proxy}= | Evaluate | sys.modules['selenium.webdriver'].Proxy() | sys, selenium.webdriver |
| ${proxy.http_proxy}= | Set Variable | localhost:8888 | |
| Create Webdriver | Firefox | proxy=${proxy} | |
| # use a proxy for PhantomJS | | | |
| ${service args}= | Create List | --proxy=192.168.132.104:8888 | |
| Create Webdriver | PhantomJS | service_args=${service args} | |
Example for Robot Framework < 2.8:
| # debug IE driver | | | |
| ${kwargs}= | Create Dictionary | log_level=DEBUG | log_file=%{HOMEPATH}${/}ie.log |
| Create Webdriver | Ie | kwargs=${kwargs} | |
"""
if not isinstance(kwargs, dict):
raise RuntimeError("kwargs must be a dictionary.")
for arg_name in kwargs:
if arg_name in init_kwargs:
raise RuntimeError("Got multiple values for argument '%s'." % arg_name)
init_kwargs[arg_name] = kwargs[arg_name]
driver_name = driver_name.strip()
try:
creation_func = getattr(webdriver, driver_name)
except AttributeError:
raise RuntimeError("'%s' is not a valid WebDriver name" % driver_name)
self._info("Creating an instance of the %s WebDriver" % driver_name)
driver = creation_func(**init_kwargs)
self._debug("Created %s WebDriver instance with session id %s" % (driver_name, driver.session_id))
return self._cache.register(driver, alias)
def __init__(self, browserName='chrome', executable_path=None, remoteAddress=None):
"""
???????
:param browserName ??????? chrome firefox ie
:param executable_path ????
:param remoteAddress ????????
:Usage:
browser = browser('chrome') # ????
path = os.path.abspath('./driver/chromedriver.exe')
browser = browser('chrome',executable_path=path) # ???????????
browser = browser('chrome',remoteAddress='http://127.0.0.1:4444/wd/hub') # ???????????
"""
# ??driver????
driver_path = configinfo.driver_path
os.environ['PATH'] = os.environ['PATH'] + ';' + driver_path
if remoteAddress is not None:
desired_capabilities = {'platform': 'ANY', 'version': '',
'javascriptEnabled': True}
if browserName.lower() == 'chrome':
dc['browserName'] = 'chrome'
elif browserName.lower() == 'firefox':
dc['browserName'] = 'firefox'
dc['marionette'] = False
elif browserName.lower() == 'ie':
dc['browserName'] = 'internet explorer'
else:
log.error('??????????????????')
raise NameError('?????????chrome firefox ie')
self.driver = webdriver.Remote(command_executor=remoteAddress,
desired_capabilities=desired_capabilities)
log.info(browserName + '??????')
else:
# ?????????
if executable_path is not None:
dir_path = os.path.abspath(executable_path)
if os.path.isfile(dir_path):
dir_path = os.path.dirname(dir_path)
os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path
log.info(dir_path + '?????????')
if browserName.lower() == 'chrome':
self.driver = webdriver.Chrome()
elif browserName.lower() == 'firefox':
self.driver = webdriver.Firefox()
elif browserName.lower() == 'ie':
self.driver = webdriver.Ie()
else:
log.error('??????????????????')
raise NameError('?????????chrome firefox ie')
log.info(browserName + '????')