我想通过 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 绑定(bind)中都没有办法让浏览器打开文件(这会给远程驱动程序带来自己的问题),但它可以被 javascript“欺骗”。
想法是打开任何 url,然后用您自己的 html 替换页面的 html - 通过 js document.write()
。这是基于您的代码的解决方案:
// 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 使用
'
字符作为字符串边界,因此该字符自然不应出现/不应在原始源代码中编码。这可以通过将 html 作为 an argument 传递来规避。 - 源代码中的换行符会产生一个 js,它会在执行时引发
SyntaxError: Invalid or unexpected token
;因此他们must be stripped
关于php - 在 webdriver 中呈现 HTML 字符串或本地 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42201789/