我正在使用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和屏幕截图?
答案 0 :(得分:1)
您在问题中提出了不少疑问。让我试着解决所有问题。使用Selenium v3.8.1
,ghostdriver v1.2.0
和phantomjs 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"}}
强> 因此,默认情况下,要求通过PhantomJSDriver
和Ghost 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
实例。