python 使用selenium时如何使页面不加载图片和css、js、字体文件
可以通过设置Selenium的ChromeOptions来实现不加载图片和CSS、JS、字体文件。具体方法如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--disable-gpu') # 禁用GPU加速
chrome_options.add_argument('--disable-infobars') # 禁用自动化信息栏
chrome_options.add_argument('--disable-extensions') # 禁用扩展
chrome_options.add_argument('--disable-javascript') # 禁用JavaScript
chrome_options.add_argument('--disable-plugins') # 禁用插件
chrome_options.add_argument('--disable-popup-blocking') # 禁用弹出拦截器
chrome_options.add_argument('--start-maximized') # 最大化窗口
prefs = {"profile.managed_default_content_settings.images": 2, # 禁止加载图片
"profile.managed_default_content_settings.stylesheets": 2, # 禁止加载CSS
"profile.managed_default_content_settings.javascript": 2, # 禁止加载JavaScript
"profile.managed_default_content_settings.plugins": 2, # 禁止加载插件
"profile.managed_default_content_settings.popups": 2, # 禁止弹出窗口
"profile.managed_default_content_settings.geolocation": 2, # 禁止获取地理位置信息
"profile.managed_default_content_settings.notifications": 2, # 禁止弹出通知
"profile.managed_default_content_settings.media_stream": 2, # 禁止获取媒体流信息
"profile.managed_default_content_settings.media_stream_mic": 2, # 禁止获取麦克风信息
"profile.managed_default_content_settings.media_stream_camera": 2, # 禁止获取摄像头信息
"profile.managed_default_content_settings.protocol_handlers": 2, # 禁止注册协议处理程序
"profile.managed_default_content_settings.mixed_script": 2, # 禁止混合内容
"profile.managed_default_content_settings.webgl": 2, # 禁止WebGL
"profile.managed_default_content_settings.cookies": 2, # 禁止Cookie
"profile.managed_default_content_settings.automatic_downloads": 2 # 禁止自动下载
}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=chrome_options)
以上代码中,我们创建了一个ChromeOptions实例,然后通过add_argument()方法添加了一些禁用选项,比如禁用GPU加速、禁用自动化信息栏、禁用扩展等。接着,我们创建了一个字典prefs,用于设置页面内容的默认管理方式,将所有内容都设置为禁用。最后,通过add_experimental_option()方法将prefs设置添加到ChromeOptions中,并将ChromeOptions实例传递给webdriver.Chrome()方法,用于启动Chrome浏览器。这样,我们就可以在使用Selenium时禁止加载图片和CSS、JS、字体文件了
原文地址: https://www.cveoy.top/t/topic/fJiY 著作权归作者所有。请勿转载和采集!