Search code examples
javascriptpythonseleniumweb-scrapingrecaptcha

Syntax executing Javascript in python


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


Solution

  • 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)