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

本文是小编为大家收集整理的关于在Selenium/PhantomJS上执行Javascript的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用Python的Selenium Webdriver使用PhantomJS,我正在尝试在页面上执行一块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)

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

推荐答案

为执行JavaScript创建的方法称为

fyi,execute()用于发送WebDriver命令.

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

还请注意,这可能会抛出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)

本文地址:https://www.itbaoku.cn/post/1739996.html

问题描述

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)

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

推荐答案

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

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

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

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

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)