c# 使用Selenium模拟登录和操作数据的学习记录

1、添加引用

  Selenium.WebDriver

  Selenium.Chrome.WebDriver

2、执行代码:

  下面的代码是找到用户列表页,然后实现自动翻页到最后一页

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApp15
{
    class Program
    {
        static void Main(string[] args)
        {
            GrabUrlByKeyWord();

        }
        static void GrabUrlByKeyWord()
        {
            ChromeOptions options = new ChromeOptions();
            //创建chrome驱动程序
            IWebDriver webDriver = new ChromeDriver(options);
            //跳至百度
            webDriver.Navigate().GoToUrl("http://localhost:8066/Account/Logon");
            //找到页面上的搜索框 输入关键字
            webDriver.FindElement(By.Id("Account")).SendKeys("admin1");
            webDriver.FindElement(By.Id("Password")).SendKeys("123456");
            //点击搜索按钮
            webDriver.FindElement(By.Id("btnWebUser")).Click();

            webDriver.Url = "http://localhost:8066/BaseInfoManagement/User/List";

            while (true)
            {
                var isHaveNext = DoNext(webDriver);

                if (isHaveNext == false)
                {
                    break;
                }
            }
            webDriver.Close();
        }

        static bool DoNext(IWebDriver webDriver)
        {
            bool result = false;
            System.Threading.Thread.Sleep(2000);
            var nextPageButton = webDriver.FindElement(By.XPath("//a[contains(@title,'下一页')]"));
            var strClass = nextPageButton.GetAttribute("class");
            if (strClass != "k-link k-pager-nav k-state-disabled")
            {
                nextPageButton.Click();
                result = true;
            }
            System.Threading.Thread.Sleep(2000);

            return result;
        }
    }
}
原文地址:https://www.cnblogs.com/wjx-blog/p/14005716.html