2010-11-02 217 views

回答

5

HtmlUnit是一個Java庫,所以非java WebDriver綁定的唯一選擇是使用RemoteWebDriver。您需要啓動Selenium服務器並連接到它,並將HtmlUnit指定爲所需的瀏覽器。

我不是很熟悉Python,但根據http://code.google.com/p/selenium/wiki/PythonBindings它應該是這個樣子:

from selenium.remote import connect 
from selenium import HTMLUNIT 


wd = connect(HTMLUNIT, server="http://<selenium_server>:4444") 
+1

但您可以通過Python使用IE,Chrome和Firefox的驅動程序綁定。而http://code.google.com/p/selenium/wiki/PythonBindings說「Selenium的Java實現支持的所有瀏覽器都可以在Python綁定中使用」。 – 2010-11-02 21:01:05

+3

但HtmlUnit不是瀏覽器 - 它是用於HTML/Web應用程序單元測試的Java框架 – 2010-11-03 10:29:05

+0

HTMLUnit是一個瀏覽器。僅僅因爲你看不到它的渲染效果並不能使它更像瀏覽器 - 它只是意味着它是無頭的。 – 2016-11-23 17:40:29

3

我用這樣的:

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'))) 
+0

不再有效:ImportError:沒有名爲remote的模塊 – 2017-11-28 21:31:02

10

我找到了答案,在https://stackoverflow.com/a/5518175/125170

As of the 2.0b3 release of the python client you can create an HTMLUnit webdriver via a remote connection like so:

from selenium import webdriver 
driver = webdriver.Remote(
    desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT) 
driver.get('http://www.google.com') 

You can also use the HTMLUNITWITHJS capability item for a browser with Javascript support.

Note that you need to run the Selenium Java server for this to work, since HTMLUnit is implemented on the Java side.

-6

//在這種情況下,您可以使用HtmlUnitDriver。

 import org.openqa.selenium.htmlunit.HtmlUnitDriver; 

//聲明和初始化的HtmlUnitWebDriver

HtmlUnitDriver unitDriver = new HtmlUnitDriver(); 

//打開google.com網頁

unitDriver.get("http://google.com"); 
+1

Downvote,這是針對java的。 OP要求python。 – Jeflopo 2015-05-02 17:50:07

相關問題