PuppeteerSharp体验之旅
public static async Task<string> LogInAsync()
{
try
{
string ResultCookies = "";
//获取用户名
string UserName = Environment.UserName;
var currentDirectory = Path.Combine(@"C:\Users\", UserName, @"AppData\Local\Google\Chrome\Application\", "Chrome.exe");//string currentDirectory = Path.GetDirectoryName(@"C:\Users\TT\AppData\Local\Google\Chrome\Application"); //指定Chrome.exe在这目录才行
if (!File.Exists(currentDirectory))
{
currentDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
var downloadPath = Path.Combine(currentDirectory, "LocalChromium");
Console.WriteLine($"Attemping to set up puppeteer to use Chromium found under directory {downloadPath} ");
if (!Directory.Exists(downloadPath))
{
Console.WriteLine("Custom directory not found. Creating directory");
Directory.CreateDirectory(downloadPath);
Console.WriteLine("Downloading Chromium");
var browserFetcherOptions = new BrowserFetcherOptions { Host = "https://npm.taobao.org/mirrors", Path = downloadPath };//设置淘宝镜像
var browserFetcher = new BrowserFetcher(browserFetcherOptions);
await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);
if (string.IsNullOrEmpty(executablePath))
{
Console.WriteLine("Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue");
Console.ReadLine();
return "Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue";
}
Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");
//Set Path
currentDirectory = Path.Combine(executablePath, "Chromium.exe");
}
else
{
//Set Path 这里没做下载失败的判断
currentDirectory = Path.Combine(downloadPath, "Chromium.exe");
}
}
var options = new LaunchOptions
{
Headless = false,//无头
ExecutablePath = currentDirectory,//本地路径
Args = new string[]
{
"--disable-infobars",//隐藏 自动化标题
},//添加Argument 和webdriver一样吧
DefaultViewport = new ViewPortOptions
{
Width = 500,
Height = 500,
IsMobile = true,
//DeviceScaleFactor = 2
},
//SlowMo=250, // slow down by 250ms
};
using (var browser = await Puppeteer.LaunchAsync(options))
using (var page = await browser.NewPageAsync())
{
// disable images to download
//await page.SetRequestInterceptionAsync(true);
//page.Request += (sender, e) =>
//{
// if (e.Request.ResourceType == ResourceType.Image)
// e.Request.AbortAsync();
// else
// e.Request.ContinueAsync();
//};
//设置手机模式
DeviceDescriptor deviceOptions = Puppeteer.Devices.GetValueOrDefault(DeviceDescriptorName.IPhone7);
await page.EmulateAsync(deviceOptions);
//await page.SetUserAgentAsync("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
await page.GoToAsync("https://www.baidu.com/");
// 登录
Console.WriteLine("Start Login!");
await page.GetContentAsync();
//输入
//ElementHandle input = await page.WaitForSelectorAsync("#search_form_input_homepage");
//await input.TypeAsync("Lorem ipsum dolor sit amet.");
await page.TypeAsync("input[name=id]", "yourname");
await page.TypeAsync("input[name=pwd]", "yourpassword");
await Task.WhenAll(page.ClickAsync("#login"), page.WaitForNavigationAsync());
Console.WriteLine("Finish Login!");
//获取Cookies
//CookieParam[] cookies = await page.GetCookiesAsync();
Console.WriteLine(ResultCookies);
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
return ResultCookies;
}
catch (Exception ex)
{
return ex.Message;
}
}
官方代码
总有一些人过着你想要的生活
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!