How to find a varible html element executing javascript in python

85go

New member
I'm trying to use 2Captcha service to solve an h captcha V2.
Works like this:
  1. you get a value to solve the captcha
  2. Then you find a textarea element in the HTML code to insert that value (here's my problem)
  3. you insert the value in that element
  4. You press submit button and the captcha is solved
First I'm going to present a working example, then I'll present where I have the problem.
This is the HTML code to find and insert the obtained value:
textarea id="h-captcha-response" name="h-captcha-response" style="display: none;"></textarea>

This is the python code used to insert the value:
Code:
value = get_value()
insert_solution = 'document.getElementById("h-captcha-response").innerHTML="' + value + '";'
driver.execute_script(insert_solution)

What this exactly does is taking you from this:
1630571881241.png

and this is the result:
1630571894433.png

Finally you press the submit button and it's done. This example works

This is my problem: In my case the HTML document has a variable ID, like this one:

Code:
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response" style="display: none;"></textarea>

Notice that the id has an alphanumerical part (0tesbrpxsk8) that always changes making it more difficult to select.

I tried to find some regular expression to use inside of document.getElementById() With no success

I also tried to use:

document.getElementByTagName("textarea").innerHTML=".....

I'm stucked here and tried other approaches with no success because I probably because I don't implement well those solutions or they just don't work.

I'll appreciate some insights, thanks
 

Seldsang

New member
This will fill out all of those (recaptcha / hcaptcha):
Code:
driver.execute_script('''
  let [captcha] = arguments
  [...document.querySelectorAll('[name="h-captcha-response"],[name="g-recaptcha-response"]')].map(el => {
    el.innerHTML = captcha
  })
''', value)
 

85go

New member
This will fill out all of those (recaptcha / hcaptcha):
Code:
driver.execute_script('''
  let [captcha] = arguments
  [...document.querySelectorAll('[name="h-captcha-response"],[name="g-recaptcha-response"]')].map(el => {
    el.innerHTML = captcha
  })
''', value)
I get this error selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected token '...' I tried without the ... but then raises another syntax error