简体   繁体   English

有没有办法使用cookies&caches来跳过C#和Playwright的登录过程?

[英]Is there any way to use cookies&caches to skip the login process with C# and Playwright?

using Microsoft.Playwright;
using NUnit.Framework;

namespace test;
public class SkipLogin
{

    [SetUp]
    public void Setup()
    {
        
    }

    [Test]
    public async Task Test1()
    {
        using var playwright = await Playwright.CreateAsync();

        await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
        {
            Headless = false
        });
        var context = await browser.NewContextAsync(new BrowserNewContextOptions
        {
            StorageState = "userCookies.json"
        });
        var page = await context.NewPageAsync();
        await page.GotoAsync("https://example.com");
        

    }

}

I'm new to C# Playwright and I'm trying to skip the login process by using "userCookies.json".我是 C# 剧作家的新手,我正在尝试使用“userCookies.json”跳过登录过程。

So, after logging in, I stored all cookies and caches and copied them to my folder.因此,登录后,我存储了所有 cookies 和缓存并将它们复制到我的文件夹中。 After that, I want to create a browser context with my cookies. But I'm getting this:在那之后,我想用我的 cookies 创建一个浏览器上下文。但我得到这个:

System.AggregateException: One or more errors occurred. ('e' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.) (Interf...

System.AggregateException
One or more errors occurred. ('e' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.) (Interface cannot be resolved: Microsoft.Playwright.IBrowser)
  Exception doesn't have a stacktrace

I tried it with JavaScript and Playwright it could be doable,but I don't how to handle it.我用 JavaScript 和 Playwright 试过它是可行的,但我不知道如何处理它。

According to their documentation it should be possible.根据他们的文档,这应该是可能的。 I see you are using StorageState maybe try StorageStatePath instead.我看到您正在使用StorageState ,也许可以试试StorageStatePath Their example:他们的例子:

var context = await browser.NewContextAsync(new()
{
    StorageStatePath = "userCookies.json"
});

https://playwright.dev/do.net/docs/auth https://playwright.dev/do.net/docs/auth

It's not clear from their documentation, and I never used this library before and could be wrong, but I believe StorageState expects the stringified JSON and not a file path.从他们的文档中不清楚,我以前从未使用过这个库并且可能是错误的,但我相信StorageState需要字符串化的 JSON 而不是文件路径。 While StorageStatePath expects a file path / file name to the JSON and will read the file for you.虽然StorageStatePath需要 JSON 的文件路径/文件名,并且会为您读取文件。

https://www.javadoc.io/static/com.microsoft.playwright/playwright/1.12.1/com/microsoft/playwright/Browser.NewContextOptions.html#storageState https://www.javadoc.io/static/com.microsoft.playwright/playwright/1.12.1/com/microsoft/playwright/Browser.NewContextOptions.html#storageState

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

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