python 使用selenium时如何使页面不下载字体文件
您可以通过以下两种方法来禁止下载字体文件:
1.通过Chrome选项禁用字体下载:
在启动Chrome时,可以通过设置ChromeOptions来禁用字体下载。示例代码如下:
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_settings.popups": 0,
"download.default_directory": "/path/to/downloads/folder",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
"disable-popup-blocking": True,
"disable-extensions": True,
"disable-default-apps": True,
"disable-infobars": True,
"disable-notifications": True,
"disable-save-password-bubble": True,
"disable-translate": True,
"safebrowsing.disable_download_protection": True,
"enable-logging": True,
"log-level": "ALL",
"disable-logging": False}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument("--disable-save-password-bubble")
chrome_options.add_argument("--disable-translate")
chrome_options.add_argument("--safebrowsing-disable-download-protection")
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--remote-debugging-port=9222")
chrome_options.add_argument("--disable-features=VizDisplayCompositor")
driver = webdriver.Chrome(chrome_options=chrome_options)
在上面的代码中,我们使用了safebrowsing.disable_download_protection参数来禁用字体下载保护。
2.通过Chrome DevTools协议修改字体下载设置:
在使用selenium启动Chrome时,可以使用Chrome DevTools协议来修改字体下载设置。示例代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
s = Service('/path/to/chromedriver')
s.start()
caps = webdriver.DesiredCapabilities.CHROME.copy()
caps['goog:loggingPrefs'] = {'performance': 'ALL'}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('w3c', False)
driver = webdriver.Chrome(service=s, options=chrome_options, desired_capabilities=caps)
driver.execute_cdp_cmd('Page.setDownloadBehavior', {'behavior': 'allow', 'downloadPath': '/path/to/downloads/folder'})
driver.execute_cdp_cmd('Page.setDownloadBehavior', {'behavior': 'deny', 'downloadPath': '/path/to/downloads/folder', 'patterns': [
'*.woff',
'*.woff2',
'*.ttf',
'*.otf'
]}})
在上面的代码中,我们使用了Page.setDownloadBehavior命令来设置下载行为。在第一个命令中,我们允许所有文件下载。在第二个命令中,我们拒绝下载所有字体文件(.woff,.woff2,.ttf,.otf)
原文地址: https://www.cveoy.top/t/topic/fJjD 著作权归作者所有。请勿转载和采集!