编程语言
首页 > 编程语言> > php – 在webdriver中呈现HTML字符串或本地html文件

php – 在webdriver中呈现HTML字符串或本地html文件

作者:互联网

我想通过facebook / php-webdriver呈现本地HTML文件.

例如:

$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'); 

但它无法加载本地文件.

如果我能渲染HTML字符串,那真是太好了:

$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);   

但是没有传递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

每个问题的最佳解决方案是什么.

解决方法:

我认为(目前)浏览器的任何selenium绑定都没有办法打开文件(这会给远程驱动程序带来问题),但这可能会被javascript“欺骗”.

这个想法是打开任何网址,然后用你自己的 – 用js document.write()替换页面的html.这是基于您的代码的解决方案:

// 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);

免责声明 – php不是我的力量(事实上,这是我的弱点:D),所以上面的代码示例可能远非完美

几句谨慎的话

> JS使用’char作为字符串边界,因此自然不应该存在该字符/应该在原始源中编码.通过将html传递为an argument可以避免这种情况
>源代码中的换行符将产生一个js,它将引发SyntaxError:执行时出现无效或意外的令牌;因此他们must be stripped

标签:php,selenium-webdriver,selenium,webdriver,php-5-6
来源: https://codeday.me/bug/20190706/1392345.html