gpt4 book ai didi

php - Laravel Dusk - 重用浏览器及其 session 和 cookie

转载 作者:行者123 更新时间:2023-12-04 02:58:54 25 4
gpt4 key购买 nike

我刚刚使用 Laravel Dusk 测试了一个 javascript 站点。

出于某种原因想要重用当前浏览器及其 session 和 cookie(让我保持在站点上的登录状态),所以我不需要通过身份验证过程。

有什么办法可以重用当前的浏览器?

我已经搜索过这个,但我没有找到实用的信息/示例。
注意:我默认使用 Dusk 和 Google Chrome 和一个独立的 ChromeDriver(不是 Selenium)

最佳答案

我使用 Laravel Dusk 也有同样的要求。诀窍是使用 Facebook/WebDriver/Remote/RemoteWebDriver 类及其 manage() method .

伪代码:

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\WebDriverOptions;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;

//the cookie file name
$cookie_file = 'cookies.txt';

//create the driver
$process = (new ChromeProcess)->toProcess();
$process->start();
$options = (new ChromeOptions)->addArguments(['--disable-gpu','--enable-file-cookies','--no-sandbox']);
$capabilities = DesiredCapabilities::chrome()->setCapability(ChromeOptions::CAPABILITY, $options);
$driver = retry(5, function () use($capabilities) {
return RemoteWebDriver::create('http://localhost:9515', $capabilities);
}, 50);

//start the browser
$browser = new Browser($driver);
$browser->visit('https://tehwebsite.com/login');

//Cookie management - if there's a stored cookie file, load the contents
if (file_exists($cookie_file)) {
//Get cookies from storage
$cookies = unserialize(file_get_contents($cookie_file));
//Add each cookie to this session
foreach ($cookies as $key => $cookie) {
$driver->manage()->addCookie($cookie);
}
}

//if no cookies in storage, do the browser tasks that will create them, eg by logging in
$browser
->type('email', 'login@email.com')
->type('password', 'sdfsdfsdf')
->check('rememberMe')
->click('#login');

//now the cookies have been set, get and store them for future runs
if (!file_exists($cookie_file)) {
$cookies = $driver->manage()->getCookies();
file_put_contents($cookie_file, serialize($cookies));
}

关于php - Laravel Dusk - 重用浏览器及其 session 和 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com