如何在python selenium中禁用PhantomJS的屏幕截图和javascript?
我正在使用windows上的phantomJS在python/selenium框架中进行抓取。首先,我尝试使用selenium禁用javascript和screenhsots:如何在python selenium中禁用PhantomJS的屏幕截图和javascript?,javascript,python,selenium,web-scraping,phantomjs,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"] =
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
时,会话.negotiatedCapability
包括:
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:在初始化期间完成这项工作合理吗?还是我走错了路?
Q2:如果是这样,如何在onInitialized期间禁用JS和屏幕截图?您在问题中提出了很多疑问。让我试着解决所有这些问题。带有
Selenium v3.8.1
、ghostdriver v1.2.0
和phantomjs v2.1.1浏览器的简单工作流
向我们展示了以下会话。默认情况下传递negotiatedCapabilities:
“浏览器名”:“幻影”
“版本”:“2.1.1”
“司机姓名”:“幽灵司机”
“driverVersion”:“1.2.0”
“平台”:“windows-8-32位”
“javascriptEnabled”:true
“takesScreenshot”:true
“handlesAlerts”:false
“databaseEnabled”:false
“locationContextEnabled”:false
“applicationCacheEnabled”:false
“CSSSelectorEnabled”:true
“webStorageEnabled”:false
“可旋转”:false
“acceptSslCerts”:false
“nativeEvents”:true
“代理”:{“代理类型”:“直接”}
PhantomJSDriver
和Ghost Browser
组合建立成功的会话,以下功能是最低要求
然后用户可以使用DesiredCapabilities
类来调整功能。但是有一些功能是创建成功的重影浏览器
会话的最低要求
javascriptEnabled就是这样一个强制属性。直到几次发布后,Selenium才允许将javascriptEnabled属性调整为false。但是现在WebDriver
作为一名W3C推荐候选者
用户级的所需功能已不再是强制性功能
即使您尝试在用户级别调整它们
,WebDriver
也会在配置功能时将它们覆盖为默认值
因此,尽管您尝试了以下方法:
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.page.settings.javascriptEnabled"] = False
webdriver.DesiredCapabilities.PHANTOMJS["phantomjs.takesScreenshot"] = False
属性javascriptEnabled和takesScreenshot默认为必需的强制配置
更新
正如您在评论中所提到的,在建立了Ghostdriver会话(即page.onInitialized)之后,如何更改这些设置呢?直接回答是否
一旦功能
被冻结并协商以初始化浏览会话
,功能
将保持有效,直到特定的会话激活
。因此,一旦建立了会话,就不能更改任何功能
。要更改功能
您必须再次配置WebDriver
实例。非常感谢您提供的详细且易于理解的答案!您的意思是,由于GhostDriver的最低要求,一些phantomJS的帽子无法更改。在建立了Ghostdriver会话(即page.onInitialized(Q2))之后,如何更改这些内容?如果不可能,你已经有效地解决了我的问题。更新了我的答案。如果你有任何反问题,请告诉我。