Home > Back-end >  Send keys to window DOM with Selenium in python to bypass captcha
Send keys to window DOM with Selenium in python to bypass captcha

Time:09-26

I am trying to get data from a webpage (https://www.educacion.gob.es/teseo/irGestionarConsulta.do). It has a captcha at the entry which I manually solve and move to the results page. It happens that going back from the results page to the entry page does not modify the captcha if I reach the initial page with the "go back" button of the browser; but if I use the driver.back() instruction of Selenium's WebDriver, sometimes the captcha is modified - which I'd better avoid.

Clearly: I want to get access from Selenium to the DOM window (the browser), rather than to the document (or any element within the html) and send the ALT ARROW_LEFT keys to the browser (the window).

This, apparently, cannot be done with:

from selenium.webdriver import Firefox
from selenium.webdriver.common.keys import Keys

driver = Firefox()
driver.get(url)
xpath = ???
driver.find_element_by_xpath(xpath).send_keys(Keys.ALT, Keys.ARROW_LEFT)

because send_keys connects to the element on focus, and my target is the DOM window, not any particular element of the document.

I have also tried with ActionChains:

from selenium.webdriver.common.action_chains import ActionChains

action = ActionChains(driver)
action.key_down(Keys.LEFT_ALT).key_down(Keys.ARROW_LEFT).send_keys().key_up(Keys.LEFT_ALT).key_up(Keys.ARROW_LEFT)
action.perform()

This also does not work (I have tried with several combinations). The documentation states that key_down/up require an element to send keys, which if None (the default) is the current focused element. So again here, there is the issue of how to focus on the window (the browser).

I have thought about using the mouse controls, but I assume it will be the same: I know how to make the mouse reach any element in the document, but I want to reach the window/browser.

I have thought of identifying the target element through the driver.current_window_handle, but also fruitlessly.

Can this be done from Selenium? If so, how? Can other libraries do it, perhaps pyppeteer or playwright?

CodePudding user response:

Try with JavaScriptExecutor - driver.execute_script("window.history.go(-1)")

  • Related