我试图在C#中使用webdriver来自动完成一些任务。我创建了一个名为logInAutomation的方法,例如:
IWebDriver driver = new ChromeDriver();
然后当单击该按钮时,我在事件处理程序中引用该方法,如下所示:
private void testButton_Click(object sender, EventArgs e)
{
logInAutomation();
}
问题是,我需要再次引用IWebDriver,但我知道如何编码它的唯一方法是重新输入:
IWebDriver driver = new ChromeDriver();
导致另一个镀铬窗口被打开。如何在不打开新窗口的情况下在事件处理程序方法中引用IWebDriver?很抱歉,如果我的术语已关闭,我是新编码的,所以如果您需要澄清,请告诉我。
以下是整个代码:
namespace Automation_Suite
{
public partial class redSuite : Form
{
public redSuite()
{
InitializeComponent();
}
static public void logInAutomation()
{
//Opens Chrome Window and navigates to Autoloop Log in
IWebDriver driver = new ChromeDriver();
driver.Url = "DESTINATION URL";
//Finds Username field and enters username
IWebElement element = driver.FindElement(By.Name("USERNAME LOG IN"));
element.SendKeys("USERNAME");
//Finds Password field and enters password
element = driver.FindElement(By.Name("PASSWORD AUTOMATION"));
element.SendKeys("PASSWORD");
//Clicks Submit
driver.FindElement(By.Id("SUBMIT BUTTON")).Click();
}
public void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void hostedGalleryBtn_Click(object sender, EventArgs e)
{
logInAutomation();
IWebElement element = element = driver.FindElement(By.Name("COMPANY ID"));
element.SendKeys("ID NUMBER");
}
}
}
答案 0 :(得分:0)
你需要定义" driver"作为class field member,不在方法内部,而是在类范围内。
namespace Automation_Suite
{
public partial class redSuite : Form
{
private IWebDriver driver = new ChromeDriver(); //define driver here so you can use it in methods.
public redSuite()
{
InitializeComponent();
}
public void logInAutomation()
{
driver.Url = "DESTINATION URL";
//Finds Username field and enters username
IWebElement element = driver.FindElement(By.Name("USERNAME LOG IN"));
element.SendKeys("USERNAME");
//Finds Password field and enters password
element = driver.FindElement(By.Name("PASSWORD AUTOMATION"));
element.SendKeys("PASSWORD");
//Clicks Submit
driver.FindElement(By.Id("SUBMIT BUTTON")).Click();
}
public void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void hostedGalleryBtn_Click(object sender, EventArgs e)
{
logInAutomation();
IWebElement element = element = driver.FindElement(By.Name("COMPANY ID"));
element.SendKeys("ID NUMBER");
}
}
}