Selenium: PhantomJS: 网站呈现为移动网站



我正在尝试使用PhantomJS无头浏览器运行Java中的Selenium自动化脚本。该脚本在 IE11 中以满头模式运行良好。

当我使用 PhantomJS 运行脚本时,网站呈现为移动站点,元素变得不可见并且脚本失败。请建议我如何克服这种情况。

我正在使用下面的代码来实例化PhantomJS

if (browserType.equalsIgnoreCase("PhantomJS")) {                    
WebDriverManager.phantomjs().setup();
driver = new PhantomJSDriver();
driver.manage().window().maximize();            
}   

PhantomJS启动时,默认视口大小400 px wide300 px high

根据讨论中的注释 渲染不遵守视口大小 @ariya提到:

PhantomJS 中的视口大小与 WebKit 中的视口具有相同的含义。这里的网页更像是一张长纸,其中捕获了内容。但是,浏览器添加了可滚动的窗口视口的概念,从而使行为有所不同。


视口大小

根据viewportSize for PhantomJS的文档:

viewportSize {object}
This property sets the size of the viewport for the layout process. It is useful to set the preferred initial size before loading the page, e.g. to choose between 'landscape' vs 'portrait'.
Because PhantomJS is headless (nothing is shown), viewportSize effectively simulates the size of the window like in a traditional browser.

例:

var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = {
width: 480,
height: 800
};

溶液

有两种可能的解决方案,如下所示:

  • 使用所需的window size配置Web 驱动程序实例:

    driver.set_window_size(1024,68)
    
  • 更改viewportSize,如下所示:

    var phantomJSDriverService = PhantomJSDriverService.CreateDefaultService(phantomJSDirectory);
    phantomJSDriverService.phantomjs.page.viewportSize = "{ width: 1024, height: 768 }";
    var driver = new PhantomJSDriver(phantomJSDriverService);
    

最新更新