How to click hCAPTCHA checkbox with php-webdriver in PHP?

Issue

I have this code with php-webdriver library in Selenium to click hCAPTCHA’s checkbox square button but results to an error instead. See code below…

$driver = RemoteWebDriver::create($host, $capabilities);

$driver->get('https://accounts.hcaptcha.com/demo?sitekey=f5561ba9-8f1e-40ca-9b5b-a0b3f719ef34');

print ($driver->getTitle());
    
$iframe = $driver->findElement(WebDriverBy::xpath("/html/body/div[5]/form/fieldset/ul/li[2]/div/div/iframe"));  
$driver->switchTo()->frame($iframe);    

$checkbox = $driver->findElement(WebDriverBy::id('/html/body/div/div[1]/div[1]/div'));
$checkbox->click();

But results to an error below…

Fatal error: Uncaught Facebook\WebDriver\Exception\NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"/html/body/div/div[1]/div[1]/div"} 

Solution

In the step $driver->findElement(WebDriverBy::id('/html/body/div/div[1]/div[1]/div')); we are specifying to search element by id but we are passing the absoulte xpath for the element

You need to pass the id of the captcha to click on it

Your solution would look like

$driver = RemoteWebDriver::create($host, $capabilities);
$driver->get('https://accounts.hcaptcha.com/demo?sitekey=f5561ba9-8f1e-40ca-9b5b-a0b3f719ef34');
print ($driver->getTitle());
$iframe = $driver->findElement(WebDriverBy::xpath("/html/body/div[5]/form/fieldset/ul/li[2]/div/div/iframe"));  
$driver->switchTo()->frame($iframe);    
$driver->wait(5, 500)->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::cssSelector('#checkbox')));
$checkbox =  $driver->findElement(WebDriverBy::cssSelector('#checkbox'));  
$checkbox->click();

Answered By – Darshan Shah

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published