Python Selenium 优化:禁止加载图片、CSS 和 JS 文件
可以通过设置浏览器的参数来实现禁止加载图片和CSS、JS文件。具体操作如下:
- 导入selenium模块和webdriver模块:
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
- 创建浏览器选项对象,并设置禁止加载图片和CSS、JS文件:
chrome_options = Options()
chrome_options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2,
'profile.managed_default_content_settings.stylesheets': 2,
'profile.managed_default_content_settings.javascript': 2})
其中,禁止图片和CSS、JS文件的设置分别为:
'prefs', {'profile.managed_default_content_settings.images': 2,
'profile.managed_default_content_settings.stylesheets': 2,
'profile.managed_default_content_settings.javascript': 2}
- 创建WebDriver对象时,将浏览器选项对象传入:
driver = webdriver.Chrome(options=chrome_options)
完整代码示例:
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2,
'profile.managed_default_content_settings.stylesheets': 2,
'profile.managed_default_content_settings.javascript': 2})
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://www.baidu.com')
time.sleep(5)
driver.quit()
原文地址: https://www.cveoy.top/t/topic/ooUm 著作权归作者所有。请勿转载和采集!