C#中通過Selenium定位標簽的問題


剛才在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);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM