"""
------------------------------------
@Time : 2019/6/29 8:16
@Auth : linux超
@File : seleniumWebdriver.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
@QQ :
@GROUP: 878565760
------------------------------------
"""
from selenium import webdriver
dr = webdriver.Chrome() # 打开浏览器
1 class WebDriver(RemoteWebDriver):
2 """
3 Controls the ChromeDriver and allows you to drive the browser.
4
5 You will need to download the ChromeDriver executable from
6 http://chromedriver.storage.googleapis.com/index.html
7 """
8
9 def __init__(self, executable_path="chromedriver", port=0,
10 options=None, service_args=None,
11 desired_capabilities=None, service_log_path=None,
12 chrome_options=None, keep_alive=True):
13 """
14 Creates a new instance of the chrome driver.
15
16 Starts the service and then creates new instance of chrome driver.
17
18 :Args:
19 - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
20 - port - port you would like the service to run, if left as 0, a free port will be found.
21 - options - this takes an instance of ChromeOptions
22 - service_args - List of args to pass to the driver service
23 - desired_capabilities - Dictionary object with non-browser specific
24 capabilities only, such as "proxy" or "loggingPref".
25 - service_log_path - Where to log information from the driver.
26 - chrome_options - Deprecated argument for options
27 - keep_alive - Whether to configure ChromeRemoteConnection to use HTTP keep-alive.
28 """
29 if chrome_options:
30 warnings.warn('use options instead of chrome_options',
31 DeprecationWarning, stacklevel=2)
32 options = chrome_options
33
34 if options is None:
35 # desired_capabilities stays as passed in
36 if desired_capabilities is None:
37 desired_capabilities = self.create_options().to_capabilities()
38 else:
39 if desired_capabilities is None:
40 desired_capabilities = options.to_capabilities()
41 else:
42 desired_capabilities.update(options.to_capabilities())
43
44 self.service = Service(
45 executable_path,
46 port=port,
47 service_args=service_args,
48 log_path=service_log_path)
49 self.service.start()
50
51 try:
52 RemoteWebDriver.__init__(
53 self,
54 command_executor=ChromeRemoteConnection(
55 remote_server_addr=self.service.service_url,
56 keep_alive=keep_alive),
57 desired_capabilities=desired_capabilities)
58 except Exception:
59 self.quit()
60 raise
61 self._is_remote = False
1 class WebDriver(object):
2 """
3 Controls a browser by sending commands to a remote server.
4 This server is expected to be running the WebDriver wire protocol
5 as defined at
6 https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
7
8 :Attributes:
9 - session_id - String ID of the browser session started and controlled by this WebDriver.
10 - capabilities - Dictionaty of effective capabilities of this browser session as returned
11 by the remote server. See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities
12 - command_executor - remote_connection.RemoteConnection object used to execute commands.
13 - error_handler - errorhandler.ErrorHandler object used to handle errors.
14 """
15
16 _web_element_cls = WebElement
17
18 def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
19 desired_capabilities=None, browser_profile=None, proxy=None,
20 keep_alive=False, file_detector=None, options=None):
21 """
22 Create a new driver that will issue commands using the wire protocol.
23
24 :Args:
25 - command_executor - Either a string representing URL of the remote server or a custom
26 remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
27 - desired_capabilities - A dictionary of capabilities to request when
28 starting the browser session. Required parameter.
29 - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.
30 Only used if Firefox is requested. Optional.
31 - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will
32 be started with given proxy settings, if possible. Optional.
33 - keep_alive - Whether to configure remote_connection.RemoteConnection to use
34 HTTP keep-alive. Defaults to False.
35 - file_detector - Pass custom file detector object during instantiation. If None,
36 then default LocalFileDetector() will be used.
37 - options - instance of a driver options.Options class
38 """
39 capabilities = {}
40 if options is not None:
41 capabilities = options.to_capabilities()
42 if desired_capabilities is not None:
43 if not isinstance(desired_capabilities, dict):
44 raise WebDriverException("Desired Capabilities must be a dictionary")
45 else:
46 capabilities.update(desired_capabilities)
47 if proxy is not None:
48 warnings.warn("Please use FirefoxOptions to set proxy",
49 DeprecationWarning, stacklevel=2)
50 proxy.add_to_capabilities(capabilities)
51 self.command_executor = command_executor
52 if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
53 self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
54 self._is_remote = True
55 self.session_id = None
56 self.capabilities = {}
57 self.error_handler = ErrorHandler()
58 self.start_client()
59 if browser_profile is not None:
60 warnings.warn("Please use FirefoxOptions to set browser profile",
61 DeprecationWarning, stacklevel=2)
62 self.start_session(capabilities, browser_profile)
63 self._switch_to = SwitchTo(self)
64 self._mobile = Mobile(self)
65 self.file_detector = file_detector or LocalFileDetector()
1 def start_session(self, capabilities, browser_profile=None):
2 """
3 Creates a new session with the desired capabilities.
4
5 :Args:
6 - browser_name - The name of the browser to request.
7 - version - Which browser version to request.
8 - platform - Which platform to request the browser on.
9 - javascript_enabled - Whether the new session should support JavaScript.
10 - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
11 """
12 if not isinstance(capabilities, dict):
13 raise InvalidArgumentException("Capabilities must be a dictionary")
14 if browser_profile:
15 if "moz:firefoxOptions" in capabilities:
16 capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
17 else:
18 capabilities.update({'firefox_profile': browser_profile.encoded})
19 w3c_caps = _make_w3c_caps(capabilities)
20 parameters = {"capabilities": w3c_caps,
21 "desiredCapabilities": capabilities}
22 response = self.execute(Command.NEW_SESSION, parameters)
23 if 'sessionId' not in response:
24 response = response['value']
25 self.session_id = response['sessionId']
26 self.capabilities = response.get('value')
27
28 # if capabilities is none we are probably speaking to
29 # a W3C endpoint
30 if self.capabilities is None:
31 self.capabilities = response.get('capabilities')
32
33 # Double check to see if we have a W3C Compliant browser
34 self.w3c = response.get('status') is None
35 self.command_executor.w3c = self.w3c
1 def execute(self, command, params):
2 """
3 Send a command to the remote server.
4
5 Any path subtitutions required for the URL mapped to the command should be
6 included in the command parameters.
7
8 :Args:
9 - command - A string specifying the command to execute.
10 - params - A dictionary of named parameters to send with the command as
11 its JSON payload.
12 """
13 command_info = self._commands[command]
14 assert command_info is not None, 'Unrecognised command %s' % command
15 path = string.Template(command_info[1]).substitute(params)
16 if hasattr(self, 'w3c') and self.w3c and isinstance(params, dict) and 'sessionId' in params:
17 del params['sessionId']
18 data = utils.dump_json(params)
19 url = '%s%s' % (self._url, path)
20 return self._request(command_info[0], url, body=data)
21
22 def _request(self, method, url, body=None):
23 """
24 Send an HTTP request to the remote server.
25
26 :Args:
27 - method - A string for the HTTP method to send the request with.
28 - url - A string for the URL to send the request to.
29 - body - A string for request body. Ignored unless method is POST or PUT.
30
31 :Returns:
32 A dictionary with the server's parsed JSON response.
33 """
34 LOGGER.debug('%s %s %s' % (method, url, body))
35
36 parsed_url = parse.urlparse(url)
37 headers = self.get_remote_connection_headers(parsed_url, self.keep_alive)
38 resp = None
39 if body and method != 'POST' and method != 'PUT':
40 body = None
41
42 if self.keep_alive:
43 resp = self._conn.request(method, url, body=body, headers=headers)
44
45 statuscode = resp.status
46 else:
47 http = urllib3.PoolManager(timeout=self._timeout)
48 resp = http.request(method, url, body=body, headers=headers)
49
50 statuscode = resp.status
51 if not hasattr(resp, 'getheader'):
52 if hasattr(resp.headers, 'getheader'):
53 resp.getheader = lambda x: resp.headers.getheader(x)
54 elif hasattr(resp.headers, 'get'):
55 resp.getheader = lambda x: resp.headers.get(x)
56
57 data = resp.data.decode('UTF-8')
58 try:
59 if 300 <= statuscode < 304:
60 return self._request('GET', resp.getheader('location'))
61 if 399 < statuscode <= 500:
62 return {'status': statuscode, 'value': data}
63 content_type = []
64 if resp.getheader('Content-Type') is not None:
65 content_type = resp.getheader('Content-Type').split(';')
66 if not any([x.startswith('image/png') for x in content_type]):
67
68 try:
69 data = utils.load_json(data.strip())
70 except ValueError:
71 if 199 < statuscode < 300:
72 status = ErrorCode.SUCCESS
73 else:
74 status = ErrorCode.UNKNOWN_ERROR
75 return {'status': status, 'value': data.strip()}
76
77 # Some of the drivers incorrectly return a response
78 # with no 'value' field when they should return null.
79 if 'value' not in data:
80 data['value'] = None
81 return data
82 else:
83 data = {'status': 0, 'value': data}
84 return data
85 finally:
86 LOGGER.debug("Finished Request")
87 resp.close()