官方文档:https://www.selenium.dev/documentation/en/webdriver/understanding_the_components/
下面是从官方文档中翻译的一些selenium常见操作。
打开网址:
IWebDriver driver = new ChromeDriver() //样例为Chrome浏览器
driver.Navigate().GoToUrl(@“https://selenium.dev”);
获取当前URL:
driver.Url;
按下浏览器的后退按钮:
driver.Navigate().Forward();
按下浏览器的前进按钮:
driver.Navigate().Forward();
刷新当前页面:
driver.navigate().refresh();
获取浏览器当前页面标题:
driver.Title;
获取窗口句柄:
driver.CurrentWindowHandle;
切换窗口或选项卡:
//Store the ID of the original window
string originalWindow = driver.CurrentWindowHandle;
//Check we don't have other windows open already
Assert.AreEqual(driver.WindowHandles.Count, 1);
//Click the link which opens in a new window
driver.FindElement(By.LinkText("new window")).Click();
//Wait for the new window or tab
wait.Until(wd => wd.WindowHandles.Count == 2);
//Loop through until we find a new window handle
foreach(string window in driver.WindowHandles)
{
if(originalWindow != window)
{
driver.SwitchTo().Window(window);
break;
}
}
//Wait for the new tab to finish loading content
wait.Until(wd => wd.Title == "Selenium documentation");
创建新窗口(或)新选项卡:
driver.SwitchTo().NewWindow(WindowType.Tab) //打开一个新标签,切换到新标签页
driver.SwitchTo().NewWindow(WindowType.Window) //打开一个新窗口,切换到新窗口
关闭一个窗口或选项卡:
driver.Close(); //关闭标签或窗口
driver.SwitchTo().Window(originalWindow); //切换回旧标签或窗口
退出浏览器会话:
driver.Quit();
切换框架的三种方式:
案例:
<div id="modal">
<iframe id="buttonframe" name="myframe" src="https://seleniumhq.github.io">
<button>Click here</button>
</iframe>
</div>
1.使用WebElement(WebElement是最灵活的选择):
//Store the web element
IWebElement iframe = driver.FindElement(By.CssSelector("#modal>iframe"));
//Switch to the frame
driver.SwitchTo().Frame(iframe);
//Now we can click the button
driver.FindElement(By.TagName("button")).Click();
2.使用iframe id或名称属性:
//使用
IDdriver.SwitchTo().Frame(“buttonframe”);
//或者使用这个名字
driver.SwitchTo().Frame(“myframe”);
//现在我们可以单击按钮
driver.FindElement(By.TagName(“按钮”)).Click();
3.使用索引:
//切换到第二个iframe
driver.SwitchTo().Frame(1);
离开iframe:
//返回到顶层
driver.SwitchTo().DefaultContent();
获取浏览器窗口的大小(以像素为单位):
//Access each dimension individually
int width = driver.Manage().Window.Size.Width;
int height = driver.Manage().Window.Size.Height;
//Or store the dimensions and query them later
System.Drawing.Size size = driver.Manage().Window.Size;
int width1 = size.Width;
int height1 = size.Height;
恢复窗口,设置窗口大小:
driver.Manage().Window.Size = new Size(1024, 768);
得到窗口的位置(获取浏览器窗口的左上角坐标):
//Access each dimension individually
int x = driver.Manage().Window.Position.X;
int y = driver.Manage().Window.Position.Y;
//Or store the dimensions and query them later
Point position = driver.Manage().Window.Position;
int x1 = position.X;
int y1 = position.Y;
设置窗口位置:
//移动窗口左上角
driver.Manage().Window.Position = new Point(0, 0);
最大化窗口:
//移动窗口左上角
driver.Manage().Window.Maximize();
最小化窗口(最小化窗口通常隐藏窗口系统托盘中):
//移动窗口左上角
driver.Manage().Window.Minimize();
全屏窗口(类似F11):
//移动窗口左上角
driver.Manage().Window.FullScreen();