Javascript to input value into textbox instead of sendKeys() in Python - javascript

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-

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

You need to insert the variable as variable, not literal
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")

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:
You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()

Related

Google App Script new editor - string property double underlined

Probably a nube question but I have a line of code:
var c = message.substring(i, i + 1);
It works but in the new Google App Script editor, the string property "substring" has a double-underline under it, which seems to suggest that it's wrong, but it actually works!
"Show Fixes" gives me only two options - to ignore the "error" or disable checking, neither of which seems like what I want to do. Any ideas?
I think it is due to how the variable "message" is defined. I did a quick test trying to replicate your scenario and this is what I got:
With warning:
var message = 0
message = '123456789'
var c = message.substr(1, 5);
Without warning:
var message = '0'
message = '123456789'
var c = message.substr(1, 5);
Both cases have the same result without errors. If you provide more code I can check why the warning is appearing.
edit:
As you have said in the comments, your variable is being defined from the range of a SpreadSheet using getValue(), this method returns an object with the value of the cell. If you want to obtain a string you should use getDisplayValue(). You can also use the built-in method toString() to make sure that any variable is converted into a string.
References:
getValue()
getDisplayValue()

JS parse object wrapped in a string using same quotes as object keys

Consider the following event payload data returned via WS:
{
id: "1",
foo: "{"bar":"baz"}"
}
The current output of JSON.stringify(event.foo):
"{\"bar\":\"baz\"}"
Also consider the backend have no real way to return the foo value formatted differently and I need to find a way to parse the string associated to this foo key in order to access it's value of bar.
The identified problem is the fact that the quotes used to wrap the whole supposed object are the sames used in the object itself, resulting in making JSON.parse() impossible.
I'm wondering if there is a "clean" way to achieve this.
So far, I tried:
using JSON.parse() which fails due to the format of the string raising Unexpected end of JSON input
trimming external quotes and converting inner ones to single then parsing, results in same error.
using new Object(...) based on the string (trimmed of external quotes)
replacing all quotes with single ones and wrapping it again in double ones to parse it.
Any input appreciated
The problem here is the backend should really be fixed, but some reason you can not do it. Next issue is you can "fix it" on the front end, but you are putting a band aid on the problem and it will fall off when the data that comes back is not what you expect. So the solutions will be error prone unless you know the data coming back will be a specific type.
With this said, you can fix the invalid JSON that you have in your simple example with a couple of regular expressions. Problem is, if your data contains characters such as } in the text, this is going to fail.
var response = `
{
id: "1",
foo: "{"bar":"baz"}",
goo: "{"gar":"gaz"}"
}
`
var reObj = /"(\{[^}]*})"/
while (response.match(reObj)) {
response = response.replace(reObj, '$1')
}
var reKey = /^\s+(\S+):/m
while (response.match(reKey)) {
response = response.replace(reKey,'"$1":')
}
var obj = JSON.parse(response)
console.log(obj)

how to evaluate a expression x+3x-4 by passing different values x to find the output

Ho to evaluate a scientifc expression (x+3x-4+sin x) by passing different values x to find the output
Please let me know the inbuilt function that can be used in java
Well I am not going give the whole code to you, but here are some hints:
The best way to eval an expression without any external API would be using running the expression as a javascript code and get the result.
Since you just can't do sin(0) + 6 in javascript, you will have to use RegEx to replace all function name to Math.(function name here) without affecting other function name. Such as sin(0) + asin(0)will be replaced to Math.sin(0) + Math.asin(0).
The changing value of x is very simple, just use RegEx to replace the x to a value without affecting other stuff, like x + exp(1) will be turned to 0 + Math.exp(1)
User can run javascript code with your calculator if using javascript, please be careful not to allow users to do so.
Similar question have been asked before, you might want to take a look about it: Evaluating a math expression given in string form
You’re looking for the sin method present in the Math library.
An example:
Math.sin(25); // Returns ‘sin’ of the value ‘25’

Converting a String into an Object

I'm receiving a string like obj{a="foo",b="bar",c=3,d=4.0} inside a nodejs environment I'm working in and I'm trying to convert this String into a reference-able Object like this:
{
a : "foo",
b : "bar",
c : 3,
d : 4.0
}
Assigned to obj of course.
I've used a myriad of formatting tricks but whenever I call JSON.parse() I get unexpected character errors. Usually on the first alpha-character it sees.
My next step is to write several nested loops to make all of the assignments manually but I'm hoping someone can point me in the right direction on how to parse this.
EDIT: Ok there's a little more to the story and I thought I should omit it but I guess explaining everything would be helpful.
The actual data packet that I'm receiving looks like this.
ack{a="000000061",b=0,c=2.0}\rb{a=244.0,b=255,c=4.0}\rc{a=6.0,b=55,c=55}endack;
So yeah that's the actual string I'm trying to parse into three distinct accessible Objects. I know I'm having a brain fart from a long day but yeah it's giving me a run for my money right now.
First replace the "=" with ":" and remove the obj infront
str = str.replace(/=/g, ":").replace("obj{", "{")
Since it's not in correct json format (but can be read by js parser) we can't use JSON.parse but we can use eval
eval("var obj = " + str);
Obvious there are some assumptions with this technique such that = always mean colon and you won't have obj{ as text (but the latter can be fixed with a simple substring method)
Keep in mind eval is also considered evil so use at your own risk. Imagine if the user were to send bad data, they could easily get into your parser and run something malicious. But hopefully this will give you an idea or inspiration to a better solution.
You can go a step further and use
str = 'obj{a="foo",b="bar",c=3,d=4.0}'
str = str.substr(3,str.length).replace(/([{,])([\w])=/g, '$1\"$2\":');
var obj = JSON.parse(str);

Extracting values with Javascript

I have a variable called "result",
var result;
that result value is equal to following value, please presume that is just a string :)
---------result value -----------
for (;;);{
"send":1,
"payload":{
"config":{
"website":"",
"title":"welcome to site",
"website-module":1313508674538,
"manufatureid":"id.249530475080015",
"tableid":"id.272772962740259",
"adminid":100002741928612,
"offline":null,
"adminemail":"admin#website.com",
"adminame":"George",
"tags":"web:design:template",
"source":"source:design:web",
"sitelog":[],
"errorlog":0,
"RespondActionlog":0,
"map":null
},
"imgupload":""
},
"criticalerror":[0],
"report":true
}
---------result value------------
From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.
How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.
You can simply evaluate the value of the variable to obtain the values. However, please note that your current value is not valid JSON; that for(;;); at the beginning of the value invalidates the format. Remove that, and you can do this:
var object = eval('(' + resultMinusThatForLoop + ')');
alert(object.payload.config.tableid);
If that data is a string the parse it with a JSON parse. The following should get the value you want
JSON.parse(result).payload.config.tableid; // "id.272772962740259"
Edit: though, as Tejs says, the for(;;) invalidates the string and stops it from being parsed. If you can remove that, do.
You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.
You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.
If result is a javascript object and not a string, you can just use 'result.payload.config.tableid'.
If it is not, how do you get the AJAX result? Are you using XmlHttpRequest directly? Most libraries will give you a javascript object, you might be missing a flag or not sending the response back with the right content type.
If it is a string and you want to parse it manually, you should use a JSON parser. Newer browsers have one built in as window.JSON, but there is open source code for parsing it as well.
var obj = JSON.parse(result);
alert('tableid is ' + obj.payload.config.tableid);

Categories