2014-12-06 59 views
0

我喜歡在python中的webdriver中執行JavaScript。 不幸的是,他們試圖實現它的方式不起作用。 我該如何正確地做到這一點?Python中的Webdriver - 執行外部JavaScript

相應的紀錄片中指出: (http://selenium-python.readthedocs.org/en/latest/api.html

driver.execute_script(‘document.title’) 

所以我寫了下面的Python代碼:

driver = webdriver.Firefox()  
driver.get("http://google.com") 
driver.execute_script("./hello_world.js")  
driver.quit() 

在相同目錄內的相應hello_world.js:

alert('Hello, World!') 

然而,不幸的是它產生消息語法錯誤:

日誌:

Traceback (most recent call last): 
    File "/sinonJS_test.py", line 44, in <module> 
    sinon_test() 
    File "/sinonJS_test.py", line 35, in sinon_test 
    driver.execute_script("./hello_world.js") 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",  line 401, in execute_script 
{'script': script, 'args':converted_args})['value'] 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",  line 173, in execute 
    self.error_handler.check_response(response) 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response 
raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.WebDriverException: Message: syntax error 
Stacktrace: 
    at handleEvaluateEvent (http://google.com:68:11) 

解attemps: 1)嘗試來排列hello_world.js文件路徑的描述中,像添加/刪除文件的後綴, 添加/移除絕對文件路徑。不工作。

注:我確實在SO上研究了類似問題的幾條回答線索 ,但沒有一個似乎能解決我的問題。例如。有些僅涉及 非常小的腳本通過在實際的python代碼中聲明JavaScript作爲 內的字符串來解決問題。這對我來說不是一種選擇,因爲我需要執行更大的 更復雜的JavaScript(Sinon Fake Timers)。

贊一個: Selenium Webdriver: execute_script can't execute custom methods and external javascript files

回答

5

你需要給包含JavaScript作爲參數傳遞給driver.execute_script的字符串。在你的情況下,如果你想執行寫在文件內的腳本,只需讀取文件並執行即可。像這樣

driver.execute_script(open("./hello_world.js").read()) 

與hello_world.js的適當位置

希望這有助於。

+0

完美的答案。感謝您的幫助Sainath!我將在今天晚些時候發佈關於使用特定腳本的跟進問題。也許你想留意它。 – 2014-12-07 13:37:22

+0

好的,我很樂意提供幫助。你可以在發佈後發表評論嗎? – 2014-12-07 13:43:40

+0

我花了我一點時間,因爲我想自己試着解決問題。但現在我需要幫助調用JavaScript中的函數:https://stackoverflow.com/questions/27410655/webdriver-in-python-executing-function-from-external-script – 2014-12-10 20:57:14