[英]Webdriver in Python - Executing External 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!')
但是,不幸的是,它会产生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)
解决方案尝试:1)试图置换hello_world.js文件路径说明,例如添加/删除文件后缀,添加/删除绝对文件路径。 不工作
注意:的确,我在SO上研究了类似问题的多个回答线程,但似乎没有一个可以解决我的问题。 例如,一些只涉及非常小的脚本的脚本通过将JavaScript声明为实际python代码中的字符串来解决了该问题。 这不是我的选择,因为我需要执行更大,更复杂的JavaScript(Sinon Fake Timers)。
像这样: Selenium Webdriver:execute_script无法执行自定义方法和外部javascript文件
您需要提供一个包含javascript的字符串作为driver.execute_script的参数。 在您的情况下,如果要执行写在文件中的脚本,只需读取文件并执行即可。 像这样
driver.execute_script(open("./hello_world.js").read())
具有hello_world.js的适当位置
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.