admin管理员组

文章数量:1344600

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('') # 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 mands available, so I'm a bit stuck here.

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.') # 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 mands available, so I'm a bit stuck here.

Share Improve this question edited Dec 22, 2017 at 18:17 Braiam 4,49611 gold badges49 silver badges83 bronze badges asked May 28, 2015 at 13:31 RyanRyan 9856 gold badges17 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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 mands.

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

本文标签: pythonExecuting Javascript on SeleniumPhantomJSStack Overflow