Microsoft.Playwright web操作基础使用
1 //如果没有下载驱动.可以使用以下代码自动安装 (以下代码仅供参考) 2 //Microsoft.Playwright.Program.Main(new[] { "install" }); 3 var playwright = await Playwright.CreateAsync(); 4 //BrowserTypeLaunchPersistentContextOptions 不是必须的.供参考 5 BrowserTypeLaunchPersistentContextOptions bto = new BrowserTypeLaunchPersistentContextOptions { Headless = false, ExecutablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver_win32", "chrome-win", "chrome.exe") }; 6 //bto.IgnoreDefaultArgs = new[] { "--enable-automation" }; 7 //bto.IgnoreAllDefaultArgs = true; 8 var browser = await playwright.Chromium.LaunchPersistentContextAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver_win32", "webDir"), bto); 9 //https://www.selenium.dev/documentation/webdriver/browsers/chrome/ 查询浏览器的可用参数 10 11 var page = browser.Pages.First(); 12 13 14 await page.GotoAsync("https://fanyi.youdao.com/index.html#/"); 15 await page.AddScriptTagAsync(new PageAddScriptTagOptions() { Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "jquery-3.4.1.min.js") }); 16 //下载数据. 17 var down = page.RunAndWaitForDownloadAsync(async () => 18 { 19 await page.EvaluateAsync("$('.download .item:eq(0)').click()"); 20 }); 21 await Task.WhenAny(down, Task.Delay(6 * 60 * 1000)); 22 var dd = await down; 23 Stream sm = await dd.CreateReadStreamAsync(); 24 await browser.CloseAsync(); 25 await browser.DisposeAsync(); 26 playwright.Dispose();