C# 使用当前配置文件/会话填写网页表单/草稿网页
C# fill web form / scratch web page using the current profile / session
我正在尝试使用网络表单/登录等,为此我需要使用当前用户配置文件会话[来启动浏览器(例如chrome) =26=]。我找到了 2 种可能的方法,但我无法完成这两种方法的代码:)
解决方案 1
System.Diagnostics.Process.Start(url);
这将在当前会话中打开一个包含我的用户个人资料的新选项卡(完美!)。但是现在呢?我没有像 "browser" 这样的变量来通过 id 或类似的东西查找元素。接下来我可以做些什么来获得页面/浏览器的控制权?
方案二(selenium驱动)
ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=C:/Users/john/AppData/Local/Google/Chrome/User Data/Default");
g.webdriver[0] = new ChromeDriver(options);
a) 如果我不将参数 user-data-dir 与我的用户配置文件的路径一起使用,它将正常打开(默认 selenium chrome 会话),我需要在我想要的网页上登录 -> 对于企业内容来说不是一个好主意。
b) 使用此代码,它将打开一个新的 chrome 浏览器 window 以及我当前的会话/用户配置文件(完美!),但代码将失败并显示错误 "DevToolsActivePort file doesn't exist",这意味着我将无法继续做我的事情。我也尝试了很多东西,比如:
System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", @"C:\Users\john\.nuget\packages\selenium.chrome.webdriver.45.0\driver\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=C:/Users/john/AppData/Local/Google/Chrome/User Data/Default");
options.AddArguments("--no-sandbox");
options.AddArguments("--disable-dev-shm-usage");
options.AddArguments("--disable-gpu");
options.AddArguments("--headless");
options.AddArguments("--no-cache");
options.AddAdditionalCapability("useAutomationExtension", false);
g.webdriver[0] = new ChromeDriver(options);
g.webdriver[0].Manage().Window.Maximize();
g.webdriver[0].Navigate().GoToUrl(url);
我回来了,我找到了解决方案! (多亏了这个guy)
使用以下代码,您可以创建新配置文件并重新使用它们。如果您使用所需帐户(例如您的 google 帐户)登录一次,它将保持同步!所以无论您需要用它做什么,它都很棒。
要求:Selenium.WebDriver (NuGet) + chromedriver_win32(与您的 chrome 版本兼容的版本 - 手动下载)+ 在代码中编辑 "default_profile_dir" 和 "chromedriver_path"
C# 网络表单,所有代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using System.IO;
using System.Drawing.Imaging;
using System.Management;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Net;
namespace ChromeAssistant
{
public partial class form_main_chromeassistant : Form
{
public form_main_chromeassistant()
{
InitializeComponent();
}
private void btn_test_profile_Click(object sender, EventArgs e)
{
CoreDriver CD = new CoreDriver();
//Config
CD.my_port = 50150;
CD.my_name = "ChromeAssistant";
CD.ConfigureProfile();
CD.Initialize();
CD.driver.Navigate().GoToUrl("https://www.google.ro/");
}
}
#region CoreDriver
public class CoreDriver
{
public IWebDriver driver;
public string my_name { get; set; }
public int my_port { get; set; }
public string default_profile_dir = @"C:\Users\john\AppData\Local\Google\Chrome\";
public string chromedriver_path = @"C:\Users\john\.nuget\packages\chromedriver_win32\";
public string site_profile_path;
public string site_profile_path_s;
public string default_path;
public void Initialize()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
options.AddArgument("--test-type");
options.AddArgument("--silent");
options.AddArgument("user-data-dir=" + site_profile_path_s);
options.AddArgument("--disable-plugins"); // disable flash
var driverService = ChromeDriverService.CreateDefaultService(chromedriver_path);
driverService.HideCommandPromptWindow = true;
driverService.Port = my_port;
driver = new ChromeDriver(driverService, options);
//The 2 line were commented by me because I got 2 errors for them
//driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 14));
//driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(15));
//This was added by me to replace the 2 commented lines
driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 15);
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("return window.stop");
}
public void ConfigureProfile()
{
site_profile_path_s = default_profile_dir + "profile " + my_name;
site_profile_path = site_profile_path_s + @"\Default";
default_path = default_profile_dir + @"User Data\Default";
if (!Directory.Exists(site_profile_path))
{
CreateBlankProfile();
}
else
{
// copy existing chrome profile. Keep cache, extensions, etc.
CopyProfileFiles();
// but stay away from opened tabs
RemoveOpenedTabsFiles();
}
}
public void CleanUpOldProfiles()
{
DirectoryInfo di = new DirectoryInfo(default_profile_dir);
DirectoryInfo[] directories = di.GetDirectories("profile*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
try
{
Directory.Delete(folder.FullName, true);
}
catch
{
}
}
}
}
public void CreateBlankProfile()
{
// new profile direftory
CreateIfMissing();
// copy existing chrome profile. Keep cache, extensions, etc.
// but stay away from opened tabs
CopyProfileFiles();
CopyProfileFolders();
}
public void CopyProfileFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy files
List<string> file_lib = new List<string>() { "Cookies", "Login", "Preferences", "Secur" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
file.CopyTo(site_profile_path + @"\" + file.Name, true);
}
}
}
}
public void RemoveOpenedTabsFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(site_profile_path);
// copy files
List<string> file_lib = new List<string>() { "Current", "Last" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
File.Delete(file.FullName);
}
}
}
}
public void CopyProfileFolders()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy folders
List<string> folder_lib = new List<string>() { "databases", "Extension", " Storage", "Web Applications", "File System", "IndexedDB" };
DirectoryInfo[] directories = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
if (PassFileOrFolder(folder.Name, folder_lib))
{
DirectoryCopy(folder.FullName, site_profile_path + @"\" + folder.Name, true);
}
}
}
}
private void CreateIfMissing()
{
Directory.CreateDirectory(site_profile_path);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public bool PassFileOrFolder(string input, List<string> library)
{
foreach (string name in library)
{
if (input.Contains(name))
{
return true;
}
}
return false;
}
}
#endregion
}
我正在尝试使用网络表单/登录等,为此我需要使用当前用户配置文件会话[来启动浏览器(例如chrome) =26=]。我找到了 2 种可能的方法,但我无法完成这两种方法的代码:)
解决方案 1
System.Diagnostics.Process.Start(url);
这将在当前会话中打开一个包含我的用户个人资料的新选项卡(完美!)。但是现在呢?我没有像 "browser" 这样的变量来通过 id 或类似的东西查找元素。接下来我可以做些什么来获得页面/浏览器的控制权?
方案二(selenium驱动)
ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=C:/Users/john/AppData/Local/Google/Chrome/User Data/Default");
g.webdriver[0] = new ChromeDriver(options);
a) 如果我不将参数 user-data-dir 与我的用户配置文件的路径一起使用,它将正常打开(默认 selenium chrome 会话),我需要在我想要的网页上登录 -> 对于企业内容来说不是一个好主意。 b) 使用此代码,它将打开一个新的 chrome 浏览器 window 以及我当前的会话/用户配置文件(完美!),但代码将失败并显示错误 "DevToolsActivePort file doesn't exist",这意味着我将无法继续做我的事情。我也尝试了很多东西,比如:
System.Environment.SetEnvironmentVariable("webdriver.chrome.driver", @"C:\Users\john\.nuget\packages\selenium.chrome.webdriver.45.0\driver\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=C:/Users/john/AppData/Local/Google/Chrome/User Data/Default");
options.AddArguments("--no-sandbox");
options.AddArguments("--disable-dev-shm-usage");
options.AddArguments("--disable-gpu");
options.AddArguments("--headless");
options.AddArguments("--no-cache");
options.AddAdditionalCapability("useAutomationExtension", false);
g.webdriver[0] = new ChromeDriver(options);
g.webdriver[0].Manage().Window.Maximize();
g.webdriver[0].Navigate().GoToUrl(url);
我回来了,我找到了解决方案! (多亏了这个guy)
使用以下代码,您可以创建新配置文件并重新使用它们。如果您使用所需帐户(例如您的 google 帐户)登录一次,它将保持同步!所以无论您需要用它做什么,它都很棒。
要求:Selenium.WebDriver (NuGet) + chromedriver_win32(与您的 chrome 版本兼容的版本 - 手动下载)+ 在代码中编辑 "default_profile_dir" 和 "chromedriver_path" C# 网络表单,所有代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using System.IO;
using System.Drawing.Imaging;
using System.Management;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Net;
namespace ChromeAssistant
{
public partial class form_main_chromeassistant : Form
{
public form_main_chromeassistant()
{
InitializeComponent();
}
private void btn_test_profile_Click(object sender, EventArgs e)
{
CoreDriver CD = new CoreDriver();
//Config
CD.my_port = 50150;
CD.my_name = "ChromeAssistant";
CD.ConfigureProfile();
CD.Initialize();
CD.driver.Navigate().GoToUrl("https://www.google.ro/");
}
}
#region CoreDriver
public class CoreDriver
{
public IWebDriver driver;
public string my_name { get; set; }
public int my_port { get; set; }
public string default_profile_dir = @"C:\Users\john\AppData\Local\Google\Chrome\";
public string chromedriver_path = @"C:\Users\john\.nuget\packages\chromedriver_win32\";
public string site_profile_path;
public string site_profile_path_s;
public string default_path;
public void Initialize()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
options.AddArgument("--test-type");
options.AddArgument("--silent");
options.AddArgument("user-data-dir=" + site_profile_path_s);
options.AddArgument("--disable-plugins"); // disable flash
var driverService = ChromeDriverService.CreateDefaultService(chromedriver_path);
driverService.HideCommandPromptWindow = true;
driverService.Port = my_port;
driver = new ChromeDriver(driverService, options);
//The 2 line were commented by me because I got 2 errors for them
//driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 14));
//driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(15));
//This was added by me to replace the 2 commented lines
driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 15);
IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
jscript.ExecuteScript("return window.stop");
}
public void ConfigureProfile()
{
site_profile_path_s = default_profile_dir + "profile " + my_name;
site_profile_path = site_profile_path_s + @"\Default";
default_path = default_profile_dir + @"User Data\Default";
if (!Directory.Exists(site_profile_path))
{
CreateBlankProfile();
}
else
{
// copy existing chrome profile. Keep cache, extensions, etc.
CopyProfileFiles();
// but stay away from opened tabs
RemoveOpenedTabsFiles();
}
}
public void CleanUpOldProfiles()
{
DirectoryInfo di = new DirectoryInfo(default_profile_dir);
DirectoryInfo[] directories = di.GetDirectories("profile*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
try
{
Directory.Delete(folder.FullName, true);
}
catch
{
}
}
}
}
public void CreateBlankProfile()
{
// new profile direftory
CreateIfMissing();
// copy existing chrome profile. Keep cache, extensions, etc.
// but stay away from opened tabs
CopyProfileFiles();
CopyProfileFolders();
}
public void CopyProfileFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy files
List<string> file_lib = new List<string>() { "Cookies", "Login", "Preferences", "Secur" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
file.CopyTo(site_profile_path + @"\" + file.Name, true);
}
}
}
}
public void RemoveOpenedTabsFiles()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(site_profile_path);
// copy files
List<string> file_lib = new List<string>() { "Current", "Last" };
FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
if (files.Count() > 0)
{
foreach (var file in files)
{
if (PassFileOrFolder(file.Name, file_lib))
{
File.Delete(file.FullName);
}
}
}
}
public void CopyProfileFolders()
{
// default profile location
DirectoryInfo di = new DirectoryInfo(default_path);
// copy folders
List<string> folder_lib = new List<string>() { "databases", "Extension", " Storage", "Web Applications", "File System", "IndexedDB" };
DirectoryInfo[] directories = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
if (directories.Count() > 0)
{
foreach (var folder in directories)
{
if (PassFileOrFolder(folder.Name, folder_lib))
{
DirectoryCopy(folder.FullName, site_profile_path + @"\" + folder.Name, true);
}
}
}
}
private void CreateIfMissing()
{
Directory.CreateDirectory(site_profile_path);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public bool PassFileOrFolder(string input, List<string> library)
{
foreach (string name in library)
{
if (input.Contains(name))
{
return true;
}
}
return false;
}
}
#endregion
}