解决selenium传入cookies错误:InvalidCookieDomainException: Message: Cookies may only be set for the curre

这是因为cookies的domain不同造成的。去掉含有多余domain的cookie,不再报错。

def getPureDomainCookies(cookies):
    domain2cookie={}  #做一个域到cookie的映射
    for cookie in cookies:
        domain=cookie['domain']
        if domain in domain2cookie:
            domain2cookie[domain].append(cookie)
        else:
            domain2cookie[domain]=[]
    maxCnt=0
    ansDomain=''
    for domain in domain2cookie.keys():
        cnt=len(domain2cookie[domain])
        if cnt > maxCnt:
            maxCnt=cnt
            ansDomain=domain
    ansCookies=domain2cookie[ansDomain]
    return ansCookies
# 加载cookies
with open('cookies.json','r') as f:
    cookies=json.load(f)
cookies=getPureDomainCookies(cookies)
for cookie in cookies:
    browser.add_cookie(cookie)

你可能感兴趣的:(爬虫,Python)