如何将HTMLUNIT驱动器与Python的Selenium一起使用?
-
30-09-2019 - |
题
我如何告诉硒使用HTMLUNIT?
我正在运行Selenium-Server-StandalOne-2.0b1.jar作为后台的硒服务器,以及使用“ PIP Install -U selenium”安装的最新Python绑定。
Firefox一切正常。但是我想使用htmlunit,因为它的重量较轻,不需要X。这是我尝试这样做的尝试:
>>> import selenium
>>> s = selenium.selenium("localhost", 4444, "*htmlunit", "http://localhost/")
>>> s.start()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/selenium/selenium/selenium.py", line 189, in start
result = self.get_string("getNewBrowserSession", start_args)
File "/usr/local/lib/python2.6/dist-packages/selenium/selenium/selenium.py", line 223, in get_string
result = self.do_command(verb, args)
File "/usr/local/lib/python2.6/dist-packages/selenium/selenium/selenium.py", line 217, in do_command
raise Exception, data
Exception: Failed to start new browser session: Browser not supported: *htmlunit
Supported browsers include:
*firefox
*mock
*firefoxproxy
*pifirefox
*chrome
*iexploreproxy
*iexplore
*firefox3
*safariproxy
*googlechrome
*konqueror
*firefox2
*safari
*piiexplore
*firefoxchrome
*opera
*iehta
*custom
因此,问题是,HTMLUNIT驱动程序叫什么?我该如何启用?
HTMLUNIT的代码似乎是Selenium 2的来源,因此我希望默认情况下像其他浏览器一样可用。我找不到有关如何启用它的任何说明。
解决方案
使用Selenium 2.20.0.Jar服务器和匹配的Python版本,我可以通过将浏览器指定为 *模拟来使用HTMLUNITDRIVER
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
server_url = "http://%s:%s/wd/hub" % (test_host, test_port)
dc = DesiredCapabilities.HTMLUNIT
wd = webdriver.Remote(server_url, dc)
wd.get('http://www.google.com')
其他提示
从Python客户端的2.0B3版本开始,您可以通过远程连接这样的远程连接创建HTMLUNIT WebDriver:
from selenium import webdriver
driver = webdriver.Remote(
desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
driver.get('http://www.google.com')
您也可以使用 HTMLUNITWITHJS
具有JavaScript支持的浏览器的功能项目。
请注意,您需要运行Selenium Java服务器才能正常工作,因为HTMLUNIT在Java侧实施。
我这样用它:
from selenium.remote import connect
b = connect('htmlunit')
b.get('http://google.com')
q = b.find_element_by_name('q')
q.send_keys('selenium')
q.submit()
for l in b.find_elements_by_xpath('//h3/a'):
print('%s\n\t%s\n' % (l.get_text(), l.get_attribute('href')))
不隶属于 StackOverflow