繁体   English   中英

从 selenium 会话中获取 cookie

[英]Get cookies from selenium session

我想在登录后获取会话变量和 cookie。 我使用了 selenium webdriver 并成功登录。 但是如何在 selenium 登录后获取会话和 cookie。这是我的代码:

try {
            WebDriver driver = new FirefoxDriver();
            driver.get("https://pacer.login.uscourts.gov/csologin/login.jsf");
            System.out.println("the title is"+driver.getTitle());
            WebElement id= driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[1]/tbody/tr/td[2]/input"));
            WebElement pass=driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[2]/tbody/tr/td[2]/input"));
            WebElement button=driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/div[2]/button[1]"));

            id.sendKeys("USERNAME");
            pass.sendKeys("PASSWORD");
            button.click();
        } catch (Exception e) {

            e.printStackTrace();
        }

请尽快提供您的建议。

谢谢

我使用以下代码添加运行了您的代码,并且能够在我的控制台中获得以下值。

try {
        WebDriver driver = new FirefoxDriver();
        driver.get("https://pacer.login.uscourts.gov/csologin/login.jsf");
        System.out.println("the title is" + driver.getTitle());
        WebElement id = driver
                .findElement(By
                        .xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[1]/tbody/tr/td[2]/input"));
        WebElement pass = driver
                .findElement(By
                        .xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[2]/tbody/tr/td[2]/input"));
        WebElement button = driver
                .findElement(By
                        .xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/div[2]/button[1]"));

        id.sendKeys("USERNAME");
        pass.sendKeys("PASSWORD");
        button.click();

        Thread.sleep(10000);
        Set<Cookie> cookies = driver.manage().getCookies();
        System.out.println("Size: " + cookies.size());

        Iterator<Cookie> itr = cookies.iterator();
        while (itr.hasNext()) {
            Cookie cookie = itr.next();
            System.out.println(cookie.getName() + "\n" + cookie.getPath()
                    + "\n" + cookie.getDomain() + "\n" + cookie.getValue()
                    + "\n" + cookie.getExpiry());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

安慰

标题是PACER登录

尺寸:1

会话ID

/登录/

pacer.login.uscourts.gov

E44C8************************400602

空值


除了 Thread.sleep(10000) 您还可以尝试使用显式等待。 我相信网页需要一些时间来设置 cookie,因为它正忙于等待页面加载。

希望这对你有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM