在Selenium/PhantomJS上执行Javascript [英] Executing Javascript on Selenium/PhantomJS

查看:75
本文介绍了在Selenium/PhantomJS上执行Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using PhantomJS via 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:

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)

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

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

推荐答案

为执行JavaScript而创建的方法称为

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

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

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

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

请注意,如果您希望JavaScript代码返回某些内容,则需要使用return.

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

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

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

# 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)

这篇关于在Selenium/PhantomJS上执行Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆