简体   繁体   中英

How to use javascript with selenium python

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

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 element

 for(int i = 0 ;i<element.length;i++){ //change all elements element[i].value = '328 91st Street'; } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM