[英]Building a selenium chrome webdriver with parameters and passing it to other methods in C#
我是Visual Studio 2015和C#的新手,我上一次编写代码的经验大约是15年前的一个高中视觉基础班。 我被要求为其他人创建一个桌面应用程序,该应用程序可以访问网页并执行某些任务。 他们想单击应用程序中的几个按钮,而不是转到页面,并且不想看到浏览器或命令提示符。
我在Visual Studio 2015 ent中选择了Selenium和C#,因为它可以满足我无命令地无头打开chrome浏览器的需求,也可以在以后进行Office集成。 我这样做是这样的:
//Sets up chrome webdriver with hidden console and headless mode.
ChromeOptions option = new ChromeOptions();
option.AddArguments("--headless");
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
//Add "option" in ChromeDriver() to activate headless chrome \/
IWebDriver driver = new ChromeDriver(driverService);
ChromeDriver()中没有“选项”用于测试,我需要查看浏览器在此步骤中正在做什么。
虽然可以,但是它是在button_click事件中创建的。 我现在的问题是,我不知道使用该方法外部所需的所有参数来建立驱动程序的正确方法。 我也想再次使用同一驱动程序的会话,而无需重新开始。
我的最终目标是让该按钮用CheckedListBox的内容填充表单(页面的唯一部分需要更改,需要直接输入),然后再用另一个按钮将用户的选择发送到页面并生成报告。
这是相关的部分:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Report_Tool
{
public partial class ReportToolUI : Form
{
//Sets the chrome webdriver.
public static IWebDriver Driver { get; set; }
public ReportToolUI()
{
InitializeComponent();
}
public void ReportToolUI_Load(object sender, EventArgs e)
{
}
public void getListButton_Click(object sender, EventArgs e)
{
//Sets up chrome webdriver with hidden console and headless mode.
ChromeOptions option = new ChromeOptions();
option.AddArguments("--headless");
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
//Add "option" in ChromeDriver() to activate headless chrome \/
IWebDriver driver = new ChromeDriver(driverService);
//Goes to obfuscated site.
driver.Navigate().GoToUrl("obfuscated");
}}}
一次创建该网络驱动程序并在不同的button_click方法中调用它的正确方法是什么?
使用单例 :
public class Utils
{
private static IWebDriver _driver;
public static IWebDriver Driver {
get {
if (_driver == null) {
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArguments("--headless");
var commandTimeout = TimeSpan.FromSeconds(30);
_driver = new ChromeDriver(service, options, commandTimeout);
}
return _driver;
}
}
}
然后使用Utils.Driver
在任何地方访问驱动程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.