简体   繁体   中英

PHP Selenium Blocked by CORS Policy

I am trying to access a website with selenium and i am getting below error

在此处输入图像描述

And i used the following code i have tried header('Access-Control-Allow-Origin: *'); but did't work for me

require_once "phpwebdriver/WebDriver.php";    
$webdriver = new WebDriver("localhost",4444);
//$ffprofile = $webdriver->prepareBrowserProfile("");
$webdriver->connect("chrome");                            
$webdriver->get("https://healofy.com/"); sleep(3); 
$element=$webdriver->findElementBy(LocatorStrategy::id,"Baby_1_2_years");
if($element) {
    print_r($element);
    $element->click();
}

It could be you're using old php webdriver client (2013) ? which is not compatible with current selenium and browser.

use updated PHP selenium facebook/webdriver and here the setup step:

# if you have composer
composer require facebook/webdriver

# if not download composer.phar
curl -sS https://getcomposer.org/installer | php
php composer.phar require facebook/webdriver

read the github page above if it missing something.

and PHP code

<?php
namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);

$driver->get("https://healofy.com/"); 

$driver->findElement(WebDriverBy::xpath('//label[@for="Baby_1_2_years"]'))->click();
//$driver->quit();

?>

If you use Selenium webdriver and want to get image from page , but blocked by cors . You can just say Selenium to go to image url and after that take screenshot . And your image will be saved! And cors will not be a problem. Here is example code in PHP:

$img_url = '.../6028384213.jpg';    
$driver->get($img_url);
$driver->takeScreenshot('img.png');

Your image will be opened by browser and after that saved to your local computer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM