对于我的爬行项目,我尝试使用 selenium 和 python 阻止所有网站的弹出窗口。 以下 chrome_options 设置帮助我阻止了某些网站的弹出窗口,但它也阻止了某些网站的加载:
chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument('--disable-notifications')
chrome_options.add_argument("--disable-plugins")
)
chrome_options.add_experimental_option("prefs", {
"profile.default_content_setting_values.cookies": 2,
"profile.default_content_setting_values.javascript": 1,
"profile.managed_default_content_settings.notifications":2,
"profile.managed_default_content_settings.popups":2,
"profile.block_third_party_cookies": True,
"profile.default_content_setting_values.plugins": 1,
})
我尝试了多种选项,也尝试了这两个网站的加载,但它们在使用阻止所有 cookie 时加载为空白。
"profile.default_content_setting_values.cookies": 2,
"profile.managed_default_content_settings.cookies":1,
"profile.content_settings.exceptions.cookies":{
"https://www.misterspex.de/":{"setting":1},
"https://www.kabum.com.br/":{"setting":1}
如何使用 chrome_options 或使用代码中的某些内容为某些网站创建例外,同时阻止其余网站的 cookie?
我用这一行替换了 cookie 阻止选项:
"profile.default_content_setting_values.cookies": 1 if allow_cookies else
2
并将其添加到过滤网址:
if url in ["https://www.misterspex.de/", 'https://www.kabum.com.br/']:
driver = setup_driver(allow_cookies=True)
else:
driver = setup_driver(allow_cookies=False)