Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a javascript variable out of a python selenium call

I am currently using Python with selenium to monitor changes to our pbx. A value I need is being called by a javascript call and is not actually being written to html so it's been a little confusing as to how I can extract the value. If I inspect the element this is what I see

<input class="SEditorInputText" id="extension_4" maxlength="15" onkeyup="javascript:onEditNumber(this);" onchange="javascript:onPropertyChange(this);" type="text">

On the web page it displays the number 1001 which is our huntgroup number. I am assuming that number is generated by the onkeyup="javascript:onEditNumber(this) function, if so is there a way to get the output to console so that I may evaluate the number assigned?

Here's my selenium code thus far

#!/usr/bin/env python

import time
import sys, urllib2
from selenium import webdriver

driver = webdriver.Firefox()

login_username = '<username>'
login_password = '<password>'

url = '<login Url>'
scripts = '<scripts Url>'

driver.get(url)

username = driver.find_element_by_name("username")
password = driver.find_element_by_name("password")

username.send_keys(login_username)
password.send_keys(login_password)

link = driver.find_element_by_name("loginbutton")
link.click()

driver.get(scripts)

aa = driver.find_element_by_xpath(".//input[contains(@onclick, 'compsci-main-aa.aef')]").click()

opt1 = driver.find_element_by_id('extension_4')

It so far works as expected going to the section in question but like I mentioned before, I need the value of that variable. When complete this script will be running headless.

Thanks in advance.

like image 876
Ed Dunn Avatar asked Oct 31 '25 19:10

Ed Dunn


1 Answers

I can think of two approaches for this.

  1. If you know the name of the JavaScript function you want to execute, you can do something like:

    num = driver.execute_script('return onEditNumber()')

  2. If you don't know the name of the JavaScript function but you know the element and the event that triggers it, you can do:

    func_name = driver.find_element_by_id('extension_4').get_attribute('onkeyup')

    func_name = func_name[func_name.index(':')+1:] # this will strip off 'javascript:' from the string name, so now 'func_name' contains 'onEditNumber();'

    num = driver.execute_script('return ' + func_name)

And if this JavaScript function returns a value, it will be stored in 'num'

like image 176
Arier Avatar answered Nov 03 '25 11:11

Arier