Syntax executing Javascript in python

Viewed 102

I am executing javascript code in python and I have some troubles with the syntax. I suspect that the problem is with (") and (') symbols.

More explained:

In order to solve a "I'm Human" captcha, I have to insert a value in an html document. 1º I get a value:

value = get_value()

Now I have to insert that value (a string) into the html code of the webpage:

insert_solver = 'document.getElementByXpath("//textarea[@name="h-captcha-response"]").innerHTML="' + value + '";'   driver.execute_script(insert_solver)

When I execute the script I get this error:

selenium.common.exceptions.JavascriptException: Message: javascript error: missing ) after argument list

executing the script like in this example doesn't give any errors:

insertar_solucion = 'document.getElementById("g-recaptcha-response").innerHTML="' + respuesta_solver + '";'

So I suspect it's a problem with added (") and (') symbols

This is the result I want, from this enter image description here

To this: enter image description here

2 Answers

There is no method execute it is execute_script instead.

You could do probably something like this :

element = driver.find_element_by_id("g-recaptcha-response")
driver.execute_script("yout JS stuff here with element[0]", element)

Udpate 1:

You can probably break down the strings like this :

element = driver.find_element_by_id("g-recaptcha-response")
inner_html = element.get_attribute('innerHTML')
final_str = inner_html + value;

I think this works just fine. It's tricky to pass on a string containing quotes.

pre = 'document.getElementByXpath('
x_path = '//textarea[@name="h-captcha-response"]'
post = f').innerHTML="{value}";'
# alternative: post = ').innerHTML="' + value + '";'
insert_solver = pre + x_path + post
driver.execute_script(insert_solver)
Related