I am trying to execute a javascript using python selenium. I am basically trying to set the value using execute.script but somehow is it not doing anything. I want to edit the street address as you see below
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Could anyone tell me what's the issue here? I am not getting an error also
2 Answers 2
There is a more robust way of doing it - locating the element with selenium using a CSS selector and passing the WebElement as well as a value into the script as an argument:
elm = driver.find_element_by_css_selector('input[ng-model="formData.address.address1"]')
value = '328 91st Street'
driver.execute_script("arguments[0].value = 'arguments[1]';", elm, value)
Note that in your code, you have 2 major problems:
- you are passing a CSS selector into the
getElementsByClassName()call - instead, it expects you to pass a class name as a string getElementsByClassName()returns an array of elements and not a single element
Comments
This code is almost good to go...
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Just remember that getElementsByClassName will return an array...
And I guess you should use querySelector or querySelectorAll function...
// will select just one element
var element = document.querySelector('input[ng-model="formData.address.address1"]');
// will select all elements
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
getElementsByClassName you should inform a class... (I think it's hard to have a class like: ng-model="formData.address.address1")
Using querySelector
var element = document.querySelector('input[ng-model="formData.address.address1"]');element.value = '328 91st Street';//Work!!!
In case you want to iterate in these NodeLists with querySelectorAll
Basically,
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');element.value = '328 91st Street';//WON'T WORK
Do instead:
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');element[0].value = '328 91st Street'; // change the value for the first elementfor(int i = 0 ;i<element.length;i++){ //change all elements element[i].value = '328 91st Street'; }
Comments
Explore related questions
See similar questions with these tags.
getElementsByClassNamewill return you an array.... so you must do element[0] (if you want the first element)WebDriverException: Message: unknown error: Cannot set property 'value' of undefinedconsole.log(element)and you will get the array...querySelectorinstead ofgetElementsByClassName