0

I cant use send_Keys() method to input values in the current website im working on. So im trying to use javascript to input values.

i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.

i use the javascript code to input value below

driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")

and it worked.

But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?

Here is the code that i tried

ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")

I know its wrong, any help would be appreciated. My Javascript is weak.

Just some side note if anybody would be able to solve my send_keys() error. The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-

JiaHao Wang
  • 101
  • 3
  • 13
  • 1
    *"...and it worked..."* Not really; [details](http://stackoverflow.com/questions/43210254/javascript-program-works-well-in-ie-but-not-in-firefox-and-chrome-to-fill-in-i). Instead: `document.getElementById('CustCd').value = 'J590';` – T.J. Crowder Sep 09 '19 at 06:56
  • I don't do Python, but surely: `driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "'")` so `ccr_No` isn't literal text in the string...? But if `ccr_No` could contain `'` or a backslash, you'll need to escape it. – T.J. Crowder Sep 09 '19 at 06:57
  • @T.J.Crowder `setAttribute()` will work just fine. – Guy Sep 09 '19 at 07:00
  • 2
    @Guy - Read the link, the `value` attribute and the `value` property are very different animals. `setAttribute` might work as a side effect of changing the default value, but it's not correct. – T.J. Crowder Sep 09 '19 at 07:00
  • @T.J.Crowder [setAttribute](https://www.w3schools.com/jsref/met_element_setattribute.asp) *The setAttribute() method adds the specified attribute to an element* if it doesn't exist. – Guy Sep 09 '19 at 07:21
  • @Guy - Right, and the `value` **attribute** does not represent the current value of an input; it represents the *default* value of an input. There is **no** attribute that represents the *current* value, that's only gotten/set by the `value` **property**. Again, please see [the linked question's](http://stackoverflow.com/questions/43210254/javascript-program-works-well-in-ie-but-not-in-firefox-and-chrome-to-fill-in-i) answers for details. – T.J. Crowder Sep 09 '19 at 07:41
  • Possible duplicate of [How do I use python variable in a javascript?](https://stackoverflow.com/questions/28592558/how-do-i-use-python-variable-in-a-javascript) – JeffC Sep 09 '19 at 19:20

3 Answers3

1

You need to insert the variable as variable, not literal

value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")
Guy
  • 46,488
  • 10
  • 44
  • 88
  • Does this ensure the resulting JavaScript code has the value in quotes? Because it needs to be, it's not a number. Also, the kind of quote used (and backslashes) need escaping. – T.J. Crowder Sep 09 '19 at 07:00
  • @T.J.Crowder Yes, this is valid Python syntax. – Guy Sep 09 '19 at 07:01
  • That isn't what I asked. I asked if it would put the value in quotes and escape things properly. – T.J. Crowder Sep 09 '19 at 07:02
  • @T.J.Crowder It doesn't need any escaping, this is valid as it is. Python can differentiate between `"` and `'`. – Guy Sep 09 '19 at 07:03
  • It **does** require quotes, which the above doesn't produce: http://ideone.com/sv2mEr. And while the **sample** value doesn't require escaping, it's just a sample value, at least mentioning the issue is important. – T.J. Crowder Sep 09 '19 at 07:06
1

First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).

The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"

If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.

In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:

import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")

That outputs:

document.getElementById('CustCd').value = "J590";

Live Example

That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).

It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:

import json

class Example:
    foo = ""
    bar = 0

    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")

That outputs:

const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;

obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.

Live Example

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Using Javascript to input the values of a variable you can use the following solution:

ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")

An example, to input the values of a variable within Search Box of Google Home Page:

  • Code Block:

    driver.get("https://www.google.com/")
    value = 'J590'
    driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")
    
  • Browser Snapshot:

variable

You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352