您可以使用 API 从集线器获取节点的 URL。然后你只需要解析 URL 并提取主机部分。虽然 WebDriver 确实存储中心 URL,但它是在私有属性中存储的。我会尊重这一点,因此此关键字要求您传入中心 URL:
import urllib2, json
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
from urlparse import urlparse, urljoin
class Selenium2LibraryExt(object):
def get_node_hostname(self, hub_url):
'''Returns the hostname/IP of the node associated with the current browser.
`hub_url` should be the URL of the Grid hub.
'''
session_id = BuiltIn().get_library_instance('Selenium2Library')._current_browser().session_id
fragment = '/grid/api/testsession?session=%s' % session_id
query_url = urljoin(hub_url, fragment)
req = urllib2.Request(url=query_url)
resp = urllib2.urlopen(req).read()
logger.debug('GET of %s returned:\n%s' % (query_url, resp))
json_blob = json.loads(resp)
if 'proxyId' in json_blob:
proxy_id = json_blob['proxyId']
logger.info('Selenium session is executing on %s' % proxy_id)
parse_result = urlparse(proxy_id)
return parse_result.hostname
else:
raise Exception('Failed to get hostname. Is Selenium running locally? hub response: %s' % resp)
在我使用的这个关键字的版本中,我从全局变量中检索 URL,而不是像上面那样使用参数。
hub_url = BuiltIn().replace_variables('${SELENIUM GRID URL}')