Python中的Webdriver - 执行外部JavaScript

Joh*_*hon 0 javascript python selenium

我喜欢在python中的webdriver中执行JavaScript.不幸的是,我试图实现它的方式不起作用.我怎样才能正确地做到这一点?

各自的纪录片陈述:(http://selenium-python.readthedocs.org/en/latest/api.html)

driver.execute_script(‘document.title’)
Run Code Online (Sandbox Code Playgroud)

所以我编写了以下python代码:

driver = webdriver.Firefox()    
driver.get("http://google.com")
driver.execute_script("./hello_world.js")    
driver.quit()
Run Code Online (Sandbox Code Playgroud)

在相同的目录中使用相应的hello_world.js:

alert('Hello, World!')
Run Code Online (Sandbox Code Playgroud)

然而,不幸的是它产生了一个Message语法错误:

日志:

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)
Run Code Online (Sandbox Code Playgroud)

解决方案尝试:1)尝试置换hello_world.js文件路径描述,如添加/删除文件后缀,添加/删除绝对文件路径.不工作.

注意:事实上,我在SO上研究了类似问题的几个回答线程,但它们似乎都没有解决我的问题.例如,一些只涉及非常小的脚本通过将JavaScript作为实际python代码中的字符串来解决问题.这不是我的选择,因为我需要执行更大更复杂的JavaScripts(Sinon假定时器).

像这样: Selenium Webdriver:execute_script无法执行自定义方法和外部javascript文件

小智 7

您需要将包含javascript的字符串作为driver.execute_script的参数.在您的情况下,如果要执行写入文件内的脚本,只需读取文件并执行即可.像这样

driver.execute_script(open("./hello_world.js").read())
Run Code Online (Sandbox Code Playgroud)

与hello_world.js的适当位置

希望这可以帮助.