org.openqa.selenium.UnableToSetCookieException: unable to set cookie

1.

当尝试添加cookies时抛出selenium unable to set cookie错误,大多情况是在一个webDriver空域(没有访问任意一个页面)中添加cookies,我们要做的就是在赋值cookies之前保证webDriver不是一个空域,比如,让它访问一下需要共享页面的主页


作者:zoQ
来源:CSDN
原文:https://blog.csdn.net/bpz31456/article/details/81875735

2.

考虑下自己的cookie是不是有前导空格。。。。 一不小心掉进了巨坑爬了半天才出来

坑Code:
static Cookie[] resolveCookies(String s) {
        ArrayList<Cookie> cookies = new ArrayList<Cookie>();
        while (s.length() != 0) {
            int index = s.indexOf('=');
            if (index == -1)
                break;
            String cookieName = s.substring(0, index);
            int endIndex = s.indexOf(';');
            if (endIndex == -1)
                endIndex = s.length();
            String cookieValue = s.substring(index + 1, endIndex);
            cookies.add(new Cookie(cookieName, cookieValue));
            s = s.substring(endIndex + 1);
        }
        return cookies.toArray(new Cookie[0]);
    }

调用

resolveCookies("_jc_save_fromStation=%u97F6%u5173%u4E1C%2CSGQ; _jc_save_toStation=%u957F%u6625%2CCCT; _jc_save_fromDate=2019-08-16;")

疯狂出异常

在后面加上:

		cookies = new Cookie[3];
        cookies[0] = new Cookie("_jc_save_fromStation", "%u97F6%u5173%u4E1C%2CSGQ");
        cookies[1] = new Cookie("_jc_save_toStation", "%u957F%u6625%2CCCT");
        cookies[2] = new Cookie("_jc_save_fromDate", "2019-08-16");

又好了,,鬼故事一样的奇怪。检查许久resolve函数,以为出在ArrayList的问题,。。结果。。。。是前导空格!

更正后:
static Cookie[] resolveCookies(String s) {
        ArrayList<Cookie> cookies = new ArrayList<Cookie>();
        while (s.length() != 0) {
            int index = s.indexOf('=');
            if (index == -1)
                break;
            String cookieName = s.substring(0, index).trim();
            int endIndex = s.indexOf(';');
            if (endIndex == -1)
                endIndex = s.length();
            String cookieValue = s.substring(index + 1, endIndex).trim();
            cookies.add(new Cookie(cookieName, cookieValue));
            s = s.substring(endIndex + 1);
        }
        return cookies.toArray(new Cookie[0]);
    }

你可能感兴趣的:(Java,错误解决)