4

I want to render a local HTML file by facebook/php-webdriver.

For example:

$host = 'http://phantomjs:8910/wd/hub'; // webdriver server is on another host
$driver = RemoteWebDriver::create($this->host, DesiredCapabilities::phantomjs());
$driver->get('file:///tmp/test.html'); 

But it can not load the local file.

It is great that if I could render HTML string:

$text = <<<EOT
<html><head><title>Test HTML</title></head><body><div>TEST BODY</div></body></html>
EOT;
$driver = RemoteWebDriver::create($this->host, DesiredCapabilities::phantomjs());
$driver->getHTML($text);   

But there no function to pass it HTML String.

Php-webdriver version: ^1.3
PHP version: 5.6
Selenium server version: Docker image of wernight/phantomjs:2.1.1
Operating system: Debian

What is the best solution for each of these problems.

Arash Mousavi
  • 2,110
  • 4
  • 25
  • 47

1 Answers1

1

I don't think there's (currently) a way in any of the selenium bindings for the browser to open a file (which would bring its own problems for remote drivers), yet that can be "tricked" by a javascript.

The idea is to open any url, and then to substitute the page's html with your own - through js document.write(). Here's a solution based on your code:

// the target html - in the sample it's just a string var
// in the final version - read it from the file system
$text = <<<EOT
<html><head><title>Test HTML</title></head><body><div>TEST BODY</div></body>
</html>
EOT;    
// the JS we will use to change the html
$js = sprintf("document.write('%s);",$text);

// get the driver
$host = 'http://phantomjs:8910/wd/hub'; // webdriver server is on another host
$driver = RemoteWebDriver::create($this->host, DesiredCapabilities::phantomjs());

// open a generic site, you know is reachable
$driver->get('http://google.com');
// and now, just change the source through JS's document.write()
$driver->executeScript($js);

Disclaimer - php is not my strength (in fact, it's my weakness :D), so the code sample above may very well be far from perfect

A few words of caution

  • the JS is using the ' char as string boundary, so naturally that character should not be present/should be encoded in the original source. This can be circumvented by passing the html as an argument
  • newlines in the source will produce a js which will raise SyntaxError: Invalid or unexpected token on execution; thus they must be stripped
Community
  • 1
  • 1
Todor Minakov
  • 19,097
  • 3
  • 55
  • 60