在 Selenium/PhantomJS 上执行 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30508045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:18:20  来源:igfitidea点击:

Executing Javascript on Selenium/PhantomJS

javascriptpythonseleniumselenium-webdriverphantomjs

提问by Ryan

I'm using PhantomJSvia Selenium Webdriver in Python and I'm trying to execute a piece of JavaScript on the page in hopes of returning a piece of data:

PhantomJS在 Python 中通过 Selenium Webdriver使用,我试图在页面上执行一段 JavaScript 以希望返回一段数据:

from selenium import webdriver

driver = webdriver.PhantomJS("phantomjs.cmd") # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('http://google.com') # EXAMPLE, not actual URL

driver.save_screenshot('screen.png') # save a screenshot to disk
jsres = driver.execute('$("#list").DataTable().data()')
print(jsres)

However when run, it reports KeyError. I was unable to find much documentation on the commands available, so I'm a bit stuck here.

但是在运行时,它报告KeyError. 我找不到关于可用命令的大量文档,所以我有点卡在这里。

回答by alecxe

The method created for executing javascript is called execute_script(), not execute():

为执行 javascript 创建的方法被调用execute_script(),而不是execute()

driver.execute_script('return $("#list").DataTable().data();')

FYI, execute()is used internally for sending webdriver commands.

仅供参考,execute()在内部用于发送 webdriver 命令。

Note that if you want something returned by javascript code, you need to use return.

请注意,如果您想要 javascript 代码返回的内容,则需要使用return.

Also note that this can throw Can't find variable: $error message. In this case, locate the element with seleniumand pass it into the script:

另请注意,这可能会引发Can't find variable: $错误消息。在这种情况下,使用 定位元素selenium并将其传递到脚本中:

# explicitly wait for the element to become present
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "list")))

# pass the found element into the script
jsres = driver.execute_script('return arguments[0].DataTable().data();', element)
print(jsres)