skip to Main Content

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!

2

Answers


  1. The interactive console is a read-eval-print loop, it automatically prints the value of an expression you type.

    But Selenium doesn’t automatically return values. The JavaScript needs a return statement to return the value.

    self.driver.execute_script("return document.getElementsByName('url')[0].value")
    
    Login or Signup to reply.
  2. 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"
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search