Querying browser console and Selenium return different values

I have this HTML page with a text box:

enter image description here

<h2>Step 2:</h2>
<p>Enter the URL for the language here: <input type="text" size="80" name="url"></p>

As you can see from the HTML code, the text box does not have any values when it’s loaded. However, it is modified externally by a user. Now after this external change I would like to read the updated amount.

I can see the modified text through the browser console:

> document.getElementsByName("url")[0].value
"http://www.ethnologue.com/show_language.asp?code=pag" 

So I was assuming that I can do the same thing via Selenium as well:

self.driver.execute_script("document.getElementsByName('url')[0].value")

Which unfortunately returns None.

Looking for your suggestions. Thanks!

>Solution :

In Selenium, when you use the execute_script method to run JavaScript code, you need to explicitly return a value from the JavaScript code using the return statement in order to capture the result in your code. Here’s how you can modify your code to capture the value of the input field using Selenium:

url_value = self.driver.execute_script(
"return document.getElementsByName('url')[0].value"
)

Leave a Reply