How to find a varible html element executing javascript in python

911 views Asked by At

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:

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: enter image description here

and this is the result: enter image description here

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:

<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

2

There are 2 answers

2
pguardiario On BEST ANSWER

This will fill out all of those (recaptcha / hcaptcha):

driver.execute_script('''
  let [captcha] = arguments
  [...document.querySelectorAll('[name="h-captcha-response"],[name="g-recaptcha-response"]')].map(el => {
    el.innerHTML = captcha
  })
''', value)
5
Lars Flieger On

Try this:

const textarea = document.querySelector('[id^="h-captcha-response-"]')
textarea.value = "This is inside the textarea!"
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response"></textarea>

  • First of all: You set the value of an textarea with textarea.value = "some value"
  • You should use document.querySelector() to select elements. (You have much more abilities there)
  • You can select id starting with, with this query: [id^="start"]