Skip to main content
 首页 » 编程设计

python之如何像开发人员工具扩展一样从 Firefox 中删除所有 CSS 样式

2025年05月04日12sharpest

我知道之前有人问过这个问题,问题是没有一个解决方案能像我需要的开发人员工具扩展一样完成工作。这是通过进入 WebDeveloper 扩展菜单并单击 css 部分中的“禁用所有样式”来实现的。

为了某些自动化,我需要页面看起来像这样。

Needed Format (No CSS styling at all)

第一个解决方案是

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile 
 
def disableImages(self): 
## get the Firefox profile object 
firefoxProfile = FirefoxProfile() 
## Disable CSS 
firefoxProfile.set_preference('permissions.default.stylesheet', 2) 
## Disable images 
firefoxProfile.set_preference('permissions.default.image', 2) 
## Disable Flash 
firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 
                              'false') 
## Set the modified profile while creating the browser object  
self.browserHandle = webdriver.Firefox(firefoxProfile) 

但是,这只会删除一些图像,而不是您在下面看到的所有内容。

1st Solution

然后我找到了一个脚本

var queries = ['link[rel=stylesheet][href]', 'style']; 
for (var i = 0; i < queries.length; i++) { 
    var remove = document.querySelectorAll(queries[i]); 
    for (var j = 0; j < remove.length; j++) { 
        remove[j].outerHTML = ''; 
    } 
} 
var inline = document.querySelectorAll('*[style]'); 
for (var i = 0; i < inline.length; i++) { 
    inline[i].removeAttribute('style'); 
} 

关于它如何工作的完整解释在这个答案 Disable styling on Google Search with Selenium FirefoxDriver 上结果还是不一样。

2nd Solution

任何帮助将不胜感激?提前致谢。

请您参考如下方法:

看来你们很接近。

除了您使用的设置之外,我还添加了两个额外的首选项,并且我能够实现预期的结果,即摆脱所有 CSS 样式 < em>火狐。

  • 代码块:

    from selenium import webdriver 
     
    firefoxProfile = webdriver.FirefoxProfile() 
    firefoxProfile.set_preference('permissions.default.stylesheet', 2) 
    firefoxProfile.set_preference('permissions.default.image', 2) 
    firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false') 
    firefoxProfile.set_preference("permissions.default.script", 2); 
    firefoxProfile.set_preference("javascript.enabled", False); 
    browserHandle = webdriver.Firefox(firefox_profile=firefoxProfile, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe') 
    browserHandle.get('https://play.google.com/store') 
    
  • 浏览器快照: