Python中的Webdriver执行外部JavaScrip

2024-04-24 07:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢用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)

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

注:事实上,我在这里研究了几个类似问题的答案 就这样,但他们似乎都没有解决我的问题。E、 g.一些只涉及 非常小的脚本通过将JavaScript声明为 实际的python代码。这不是我的选择,因为我需要执行更大的 更复杂的JavaScripts(Sinon假计时器)。

就像这个: Selenium Webdriver: execute_script can't execute custom methods and external javascript files


Tags: 文件inpytesthttphelloworldexecute