C# Selenium自动化

==================【技术点】==================

1、HttpWebRequest

2、HttpWebResponse

3、WebClient

4、HtmlAgilityPack

5、Selenium

Selenium.RC

Selenium.Support

Selenium.WebDriver

Selenium.WebDriver.ChromeDriver

==================【自动化测试】==================

1、WebBrowser

/// 让WebBrowser跳转到指定页面地址
WebBrowser1.Navigate(http://blog.sina.com.cn/shushx),
/// 向控件填入值
/// 文本框
WebBrowser1.document.getElementByIdx_x("txtUserName").InnerText = "shushx";
/// 下拉框
WebBrowser1.document.getElementByIdx_x("lAge").SetAttribute("value", "question1");
/// 复选框
WebBrowser1.document.getElementByIdx_x("chkSingle").SetAttribute("Checked", "True");
/// 多选框
WebBrowser1.document.getElementByIdx_x("chkMang").SetAttribute("checked", "checked");
/// 点击某个按钮
WebBrowser1.document.getElementByIdx_x("submit").InvokeMember("click");

2、获取单个元素

find_element_by_id : 通过元素id获取
find_element_by_name : 通过元素的name属性获取
find_element_by_class : 通过元素的class属性获取
find_element_by_css_selector : 通过CSS选择器获取元素
find_element_by_tag_name : 通过标签获取元素
find_element_by_link_text : 通过链接中的文本属性获取元素
find_element_by_partial_link_text : 通过链接中所包含的文本内容进行模糊查询获取元素
find_element_by_xpath : 通过xpath获取元素

a = driver.find_element_by_id("u1")
b = driver.find_element_by_name("wd")
c = driver.find_element_by_class_name("mnav")
d = driver.find_element_by_tag_name("a")
f = driver.find_element_by_css_selector("#u1 > a:nth-child(1)")
g = driver.find_element_by_partial_link_text("新")
h = driver.find_element_by_link_text("新闻")
i = driver.find_element_by_xpath("//*[@id=\"u1\"]/a[1]")

/// 单个元素
driver.FindElement(By.XPath("//*[@name='user_name']"));
driver.FindElement(By.CssSelector("//*[@id='u1']/a[1]"));
driver.FindElement(By.CssSelector("#u1 > a:nth-child(1)"));
driver.FindElement(By.CssSelector(".menu-bar > .menu-item:nth-child(2)")).Click();
driver.FindElement(By.CssSelector(".content-group:nth-child(1) .content-info")).Click();
driver.FindElement(By.CssSelector(".course-item:nth-child(1) img")).Click();
driver.FindElement(By.CssSelector($".chaper:nth-child({w1}) > .li:nth-child({ww1+1}) .text1")).GetAttribute("textContent");
driver.FindElement(By.CssSelector(".xgplayer-time > span:nth-child(2)")).GetAttribute("innerHTML");
driver.FindElement(By.Id("kw")).GetCssValue("width");/// 获取 css 宽度
driver.FindElement(By.LinkText("登录")).Click();

3、获取多个元素,列表数据

/// 多个元素
driver.FindElements(By.CssSelector("#myTab > li > a"));
driver.FindElements(By.CssSelector(".news"));
driver.FindElements(By.TagName("li"));
driver.FindElements(By.TagName("iframe"));

4、循环



//
var list = driver.FindElements(By.CssSelector("#myTab > li > a"));
if (list != null && list.Count > 0)
{
    for (int i = 0; i < list.Count; i++)
    {
        string name = list[i].Text;
        string href = list[i].GetAttribute("href");
    }
}

5、js操作 焦点

public class Test
{
    public IWebDriver driver { get; private set; }
    public IDictionary vars { get; private set; }
    public IJavaScriptExecutor js { get; private set; }

    public Test()
    {
        driver = new ChromeDriver();
        js = (IJavaScriptExecutor)driver;
        vars = new Dictionary();
    }

    string url = driver.Url;
    js.ExecuteScript($"window.open('{currentUrl}')");
    js.ExecuteScript($"window.open('{url}','_blank');");//新标签页打开页面
    driver.SwitchTo().Window(driver.WindowHandles.Last());//切换到最新的标签页
    /// Chrome关闭当前窗口
    js.ExecuteScript("setInterval('window.location.href=\"about:blank\";window.close();', 3000);");

    /// 设置焦点
    js.ExecuteScript("$(arguments[0]).focus()", driver.FindElement(By.Id("vcode")));
}

6、鼠标拖拽【进度条】,鼠标右键

var element = driver.FindElement(By.Id("ku"));
Actions action = new Actions(driver);
/// 水平拖拽,横向拖拽,悬停
action.MoveToElement(element, 100, 0).ClickAndHold().Release().Perform();

/// 选择元素,鼠标右键,ContextClick
var imgElement = driver.FindElement(By.CssSelector(".login-code"));
Actions actions = new Actions(driver);
actions.MoveToElement(imgElement).Perform();
actions.ContextClick(imgElement).Build().Perform();

7、Cookie操作

/// 添加Cookie
driver.Manage().Cookies.AddCookie(new Cookie("BDUSS", "123456789"));

/// 获取Cookie
var cookies = driver.Manage().Cookies.AllCookies;
if (cookies != null)
{
    foreach(var item in cookies)
    {
        string name = item.Name;
        string value = item.Value;
    }
}

8、iframe、窗口选择,切换,查询所有窗口

driver.SwitchTo().Frame(0);
driver.SwitchTo().ParentFrame();
driver.SwitchTo().Frame("iframe的name属性");

/// 注意:无id,无name,先定位iframe元素,再切换到iframe
driver.SwitchTo().Frame(driver.FindElement(By.XPath("//*[@name='user_name']")));

/// 注意:无id,无name,先定位iframe元素,再切换到iframe
var element = driver.FindElement(By.TagName("iframe")[0])
driver.SwitchTo().Frame(element);

/// 跳出所有 iframe,回到主界面
driver.SwitchTo().DefaultContent();
/// 关闭当前选项卡
driver.SwitchTo().Window(driver.WindowHandles.Last()).Close();

/// 查询所有窗口
for (int i = driver.WindowHandles.Count; i > 1; i--)
{
    if (i > 2)
    {
        //driver.SwitchTo().Window(driver.WindowHandles.Last()).Close();//关闭最后一个选项卡
        driver.SwitchTo().Window(driver.WindowHandles[i - 1]).Close();
    }
}

9、图片右键图片另存为

using WindowsInput;
using WindowsInput.Native;

var imgElement = driver.FindElement(By.CssSelector(".login-code"));
Actions actions = new Actions(driver);
actions.MoveToElement(imgElement).Perform();
actions.ContextClick(imgElement).Build().Perform();
System.Threading.Thread.Sleep(2000);
var sim = new InputSimulator();

/// chrome 浏览器下载地址 C:\Users\Administrator\Downloads
sim.Keyboard.KeyPress(VirtualKeyCode.VK_V).Sleep(2000).TextEntry("测试图片").Sleep(1000).KeyPress(VirtualKeyCode.RETURN);

10、.NET WinForm Button按钮单击事件

private void btnLogin_Click(object sender, EventArgs e)
{
    btnLogin.Enabled = false;

    #region ChromeOptions 参数
    ChromeOptions options = new ChromeOptions();
    options.AddArguments("--test-type", "--ignore-certificate-errors");//https
    options.AddExcludedArgument("enable-automation");//关闭安全提示
    options.AddAdditionalOption("useAutomationExtension", false);//取消 chrome正受到自动测试软件的控制的信息栏
    options.AddUserProfilePreference("credentials_enable_service", false);//禁用浏览器的保存密码选项
    options.AddArguments("lang=zh_CN.UTF-8");
    options.AddArgument("--user-agent=Mozilla/5.0 HAHA");    // 配置对象添加替换User-Agent的命令
    //options.AddArgument("--window-size=1366,768");           // 设置浏览器分辨率(窗口大小)
    options.AddArgument("--start-maximized");//启动即最大化
    options.AddArgument("--disable-popup-blocking");//禁用弹出拦截
    options.AddArgument("no-sandbox");//关闭沙盘
    options.AddArgument("disable-extecsions");//扩展插件检测
    options.AddArgument("no-default-browser-check");//默认浏览器检测
    options.AddArgument("disable-infobars");//去掉提示:Chrome正收到自动测试软件的控制
    options.AddArgument("--incognito");//隐身模式(无痕模式)
    options.AddArgument("blink-settings=imagesEnabled=false");  //不加载图片, 提升速度

    //options.AddArgument("--proxy-server=http://115.239.102.149:4214"); //代理
    //options.AddAdditionalOption("authorization", "Bearer C_LaJqWZ7MWjxHON7vYu-UZ2AKmvxuWnG_u05UHEutY");
    //禁用浏览器的保存密码选项
    options.AddUserProfilePreference("credentials_enable_service", false);
    #endregion

    var chromeDriverService = ChromeDriverService.CreateDefaultService();//关闭黑窗口
    chromeDriverService.HideCommandPromptWindow = true;//关闭黑色cmd窗口
    var driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeDriverService, options);
    driver.Navigate().GoToUrl("https://10.10.10.10:8572/emer_web/#/login");//打开网站

    #region 1 By.Id ok
    driver.FindElement(By.Id("account")).SendKeys("zhangsan");
    driver.FindElement(By.Id("password")).SendKeys("123456");
    #endregion

    #region 2 By.Name ok
    //driver.FindElement(By.Name("user_name")).SendKeys("zhangsan");
    //driver.FindElement(By.Name("password")).SendKeys("123456");
    #endregion

    #region 3 By.CssSelector ok
    //driver.FindElement(By.CssSelector("[type='text'][name='user_name']")).SendKeys("zhangsan123");
    //driver.FindElement(By.CssSelector("[type='password'][name='password']")).SendKeys("123456");
    #endregion

    #region 4 By.CssSelector ok
    driver.FindElement(By.CssSelector("#myTab_Content0 li:nth-child(3) > .main1f2mr1 > a:nth-child(3)")).Click();
    #endregion

    #region 5 By.XPath ok
    //driver.FindElement(By.XPath("//*[@name='user_name']")).SendKeys("zhangsan456");
    //driver.FindElement(By.XPath("//*[@name='password']")).SendKeys("123456");
    #endregion

    #region 6 By.XPath ok
    //driver.FindElement(By.XPath("//*[@type='text' and @name='user_name']")).SendKeys("zhangsan");
    //driver.FindElement(By.XPath("//*[@type='password' and @name='password']")).SendKeys("123456");
    #endregion

    #region 7 By.XPath ok
    //driver.FindElement(By.XPath("//input[@name='user_name']")).SendKeys("zhangsan");
    //driver.FindElement(By.XPath("//input[@name='password']")).SendKeys("123456");
    #endregion

    #region 8 By.XPath ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div/div/div/input")).SendKeys("zhangsan");//ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div/div/div/input[1]")).SendKeys("zhangsan");//ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div/div/div[1]/input")).SendKeys("zhangsan");//ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div[3]/div/div/input")).SendKeys("123456");//ok
    #endregion

    #region 9 By.XPath ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div/div/div/input[@name='user_name']")).SendKeys("zhangsan");
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/div/div/div/input[@name='password']")).SendKeys("123456");
    #endregion

    #region 10 FindElements By.CssSelector
    var list = driver.FindElements(By.CssSelector(".el-input__inner"));
    for (int i = 0; i < list.Count; i++)
    {
        if (i == 0)
            list[i].SendKeys("zhangsan");
        else if (i == 1)
            list[i].SendKeys("123456");
    }
    #endregion

    #region 11 设置控件获取焦点
    driver.ExecuteScript("$(arguments[0]).focus()", driver.FindElement(By.Id("txtCode")));
    Thread.Sleep(9000);

    while (true)
    {
        string code = driver.FindElement(By.Id("txtCode")).GetAttribute("value");
        if (!string.IsNullOrWhiteSpace(code) && code.Length == 4)
        {
            driver.FindElement(By.Id("txtCode")).SendKeys(code);
            break;
        }
        Thread.Sleep(3000);
    }
    #endregion

    #region
    driver.FindElement(By.LinkText("学习")).Click();
    #endregion

    #region
    driver.FindElement(By.CssSelector(".xgplayer-time > span:nth-child(2)")).GetAttribute("innerHTML");
    driver.FindElement(By.CssSelector($".chaper:nth-child({w1}) > .li:nth-child({ww1+1}) .text1")).GetAttribute("textContent");
    #endregion

    #region 登录事件
    //driver.FindElement(By.CssSelector("form>button")).Click();//ok
    //driver.FindElement(By.XPath("//button[@type='button']")).Click();//ok
    //driver.FindElement(By.XPath("//button")).Click();//ok
    //driver.FindElement(By.XPath("/html/body/div/div/div/div/form/button")).Click();
    //driver.FindElement(By.TagName("button")).Click();//ok
    //driver.FindElement(By.CssSelector(".el-button")).Click();//ok
    driver.FindElement(By.CssSelector(".el-button.el-button--primary.el-button--medium")).Click();//ok
    Thread.Sleep(1000);
    #endregion

    #region 选择机构
    var hospitalList = driver.FindElements(By.CssSelector(".hospitalbox"));
    if (hospitalList != null && hospitalList.Count > 0)
    {
        for (int i = 0; i < hospitalList.Count; i++)
        {
            var name1 = hospitalList[i].FindElement(By.CssSelector("p")).Text;
            var name2 = hospitalList[i].FindElement(By.TagName("p")).Text;
            var name3 = hospitalList[i].FindElement(By.XPath("/html/body/div/div/div/div/div/div/div/p")).Text;
            hospitalList[i].FindElement(By.XPath("/html/body/div/div/div/div/div/div/div")).Click();
            break;
        }
    }
    Thread.Sleep(3000);

    #endregion

    #region 退出
    //var dropdown = driver.FindElement(By.CssSelector(".el-dropdown-menu.el-popper.el-dropdown-menu--medium"));
    //var dropdownLi = dropdown.FindElements(By.TagName("li"));
    //if (dropdownLi != null && dropdownLi.Count > 0)
    //{
    //    for (int i = 0; i < dropdownLi.Count; i++)
    //    {
    //        var name1 = dropdownLi[i].FindElement(By.TagName("span")).GetAttribute("innerHTML").Replace("\r\n", "").Replace(" ", "");
    //        if (name1 == "退出系统")
    //        {
    //            driver.FindElement(By.CssSelector(".user-avatar")).Click();
    //            Thread.Sleep(1000);
    //            //dropdownLi[i].FindElement(By.TagName("span")).Click();//ok
    //            dropdownLi[i].FindElement(By.XPath("/html/body/ul/li[3]/div/span")).Click();//ok

    //            //鼠标悬停
    //            //IWebElement testDiv = dropdownLi[i].FindElement(By.TagName("span"));
    //            //Actions builder = new Actions(driver);
    //            //Actions hoverClick = builder.MoveToElement(testDiv).Click();
    //            //hoverClick.Build().Perform();
    //        }
    //    }
    //}

    #endregion

    #region 退出
    var dropdown = driver.FindElements(By.CssSelector(".dropdownWrapper"));
    if (dropdown != null && dropdown.Count > 0)
    {
        for (int i = 0; i < dropdown.Count; i++)
        {
            var name1 = dropdown[i].FindElement(By.TagName("span")).GetAttribute("innerHTML").Replace("\r\n", "").Replace(" ", "");
            var name2 = dropdown[i].FindElement(By.XPath("span")).GetAttribute("innerHTML").Replace("\r\n", "").Replace(" ", "");
            if (name1 == "退出系统")
            {
                driver.FindElement(By.CssSelector(".user-avatar")).Click();
                Thread.Sleep(1000);
                dropdown[i].FindElement(By.TagName("span")).Click();//ok
                //dropdown[i].FindElement(By.XPath("span")).Click();//ok
            }
        }
    }
    #endregion

    #region 退出 li a
    //driver.FindElement(By.XPath("//a[text()='退出']")).Click();
    //driver.FindElement(By.XPath("//a[contains(text(),'退出')]")).Click();
    driver.FindElement(By.XPath("/html/body/div/div/ul/li[2]/a")).Click();
    driver.FindElement(By.LinkText("退出")).Click();
    #endregion

    Thread.Sleep(3000);
    driver.Close();//关闭当前选项卡
    driver.Dispose();
    driver.Quit();//关闭所有选项卡

    btnLogin.Enabled = true;
}

*

*

*

你可能感兴趣的:(.Net技术,.NET,Core,Selenium,自动化)