使用Selenium在PyCharm中登录WP遇Cookie问题,求无按钮授权方案
你的代码如下:
class base_test(unittest.TestCase): def setUp(self): warnings.simplefilter('ignore', ResourceWarning) self.driver = webdriver.Chrome() self.driver.maximize_window() def test1(self): driver = self.driver f=Funciones_Globales(driver) f.nav("WP link",t) f.Tab_Xpath_valida("//input[@id='user_login']", "username", "password", t)
下面是几种无需点击按钮就能处理Cookie的方法,直接适配你的测试代码即可:
方法1:配置Chrome自动接受所有Cookie
修改setUp方法,给Chrome添加默认Cookie权限配置,跳过弹窗:
def setUp(self): warnings.simplefilter('ignore', ResourceWarning) options = webdriver.ChromeOptions() # 禁用各类通知弹窗 options.add_argument("--disable-notifications") # 设置默认允许所有Cookie,关闭第三方Cookie拦截 options.add_experimental_option("prefs", { "profile.default_content_setting_values.cookies": 1, "profile.block_third_party_cookies": False }) self.driver = webdriver.Chrome(options=options) self.driver.maximize_window()
方法2:直接添加WP验证所需Cookie
先访问WP站点根域名(必须先访问域名才能添加对应Cookie),再手动插入WP的测试Cookie:
def test1(self): driver = self.driver # 先打开WP站点根域名 driver.get("你的WP站点域名") # 添加WP内置的测试Cookie,替换成实际域名 driver.add_cookie({ "name": "wordpress_test_cookie", "value": "WP+Cookie+check", "domain": "你的WP站点域名", "path": "/" }) # 执行后续登录操作 f=Funciones_Globales(driver) f.nav("WP link",t) f.Tab_Xpath_valida("//input[@id='user_login']", "username", "password", t)
方法3:用CDP命令强制授予Cookie权限
通过Chrome开发者工具协议直接给目标站点设置Cookie权限,适合复杂场景:
def setUp(self): warnings.simplefilter('ignore', ResourceWarning) self.driver = webdriver.Chrome() self.driver.maximize_window() # 给WP站点授予Cookie权限 self.driver.execute_cdp_cmd("Network.setPermission", { "origin": "你的WP站点域名", "permission": "cookies", "setting": "granted" })
注意事项
- 所有方法中的
你的WP站点域名需要替换成实际域名(比如example.com) - 方法1是最通用的方案,大部分Cookie弹窗问题都能通过这个配置解决
- 如果用方法2不确定需要哪些Cookie,可以打开浏览器开发者工具,在登录前查看站点的Cookie列表
内容的提问来源于stack exchange,提问作者Leonardo J. M. Dugarte
相关产品推荐
相关产品推荐

