C#中通过Selenium定位<a>标签的问题

刚才在QQ群里看到有人提问,如何实现退出百度登录问题。那么之所以会有这个问题,主要是因为这个元素,如下图所示,是无法直接定位到的:

经过研究发现,要想定位到这种元素,拢共分两步:

第一步,把鼠标移到能使目标元素显示在页面上的前置元素上;

第二步,通过xpath对目标标签元素进行定位。

代码如下:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace BaiduAutoLoginOut
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver iw = new InternetExplorerDriver();
            iw.Navigate().GoToUrl("http://www.baidu.com");
            IWebElement login = iw.FindElement(By.Id("s_username_top"));
            Actions action = new Actions(iw);
            action.MoveToElement(login).Build().Perform();
            WaitUntilPageLoaded(iw, "//a[text()=' 退出 ']");
            iw.FindElement(By.XPath("//a[text()=' 退出 ']")).Click();
        }
        private static void WaitUntilPageLoaded(IWebDriver iw, string v)
        {
            try
            {
                iw.FindElement(By.XPath(v));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Thread.Sleep(1000);
                WaitUntilPageLoaded(iw, v);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/LanTianYou/p/4935709.html