如何在python selenium中禁用PhantomJS的屏幕截图和javascript?

时间:2018-01-19 05:48:24

标签: javascript python selenium web-scraping phantomjs

我正在使用Windows上的phantomJS在python / selenium框架中进行搜索。首先,我尝试使用selenium禁用javascript和screenhsots:

driver = webdriver.PhantomJS("phantomjs.exe", desired_capabilities = dcap)
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.settings.javascriptEnabled"] = False
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.takesScreenshot"] = False
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.clearMemoryCash"] = False

但是,当我查看ghostdriver.log时,Session.negotiatedCapabilities包括:

browserName:phantomjs
version:2.1.1
driverName:ghostdriver
driverVersion:1.2.0
platform:windows-7-32bit
javascriptEnabled:true   # Should be false
takesScreenshot:true     # Should be false

因此,我认为我需要在onInitialized=function()期间停用这两个参数,类似于以下代码段:

phantom_exc_uri='/session/$sessionId/phantom/execute'
driver.command_executor._commands['executePhantomScript'] = ('POST', phantom_exc_uri)
initScript="""             
this.onInitialized=function() {
    var page=this;
   ### disable javascript and screenshots here ###
}
"""
driver.execute('executePhantomScript',{'script': initScript, 'args': []})

Q1:为什么我可以在webdriver.DesiredCapabilities中设置某些 phantomJS规范,但其他人不是?这是我的错误还是一些错误?

Q2:在onInitialized期间完成此操作是合理的还是我错误的方式?

Q2:如果是这样,如何在onInitialized期间禁用JS和屏幕截图?

1 个答案:

答案 0 :(得分:1)

您在问题中提出了不少疑问。让我试着解决所有问题。使用Selenium v3.8.1ghostdriver v1.2.0phantomjs v2.1.1 Browser的简单工作流程向我们显示默认情况下会传递以下 Session.negotiatedCapabilities

  • "browserName":"phantomjs"
  • "version":"2.1.1"
  • "driverName":"ghostdriver"
  • "driverVersion":"1.2.0"
  • "platform":"windows-8-32bit"
  • "javascriptEnabled":true
  • "takesScreenshot":true
  • "handlesAlerts":false
  • "databaseEnabled":false
  • "locationContextEnabled":false
  • "applicationCacheEnabled":false
  • "cssSelectorsEnabled":true
  • "webStorageEnabled":false
  • "rotatable":false
  • "acceptSslCerts":false
  • "nativeEvents":true
  • "proxy":{"proxyType":"direct"}}

因此,默认情况下,要求通过PhantomJSDriverGhost Browser组合建立成功的会话,以下 Capabilities 是最低要求。

然后,用户可以使用DesiredCapabilities课程来调整功能。但是,某些功能最低要求可以创建成功的Ghost Browser会话。

javascriptEnabled 是强制性的此类属性。直到几个版本Selenium允许将 javascriptEnabled 属性调整为 false 。但现在 WebDriver 成为 W3C Recommendation Candidate ,强制功能无法再通过用户级DesiredCapabilities覆盖。

即使您尝试在user level处调整它们,WebDriver也会在配置capabilities时将其覆盖为默认值。

所以,尽管你已经尝试了以下内容:

webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.settings.javascriptEnabled"] = False
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.takesScreenshot"] = False

属性 javascriptEnabled takeScreenshot 默认为必需的强制配置。

更新

正如您在评论What about changing those AFTER the Ghostdriver session is established, i.e. page.onInitialized中提到的,直接答案是

capabilities 冻结协商以初始化Browsing Session capabilities保持为真,直到特定{{1} }}。因此,session is active之后您无法更改capabilities中的任何内容。要更改session is established,您必须再次配置capabilities实例。