Selenium C# 找不到 ID 或 Title
本文关键字:Title ID 找不到 Selenium | 更新日期: 2023-09-27 18:31:00
我设法打开了一个火狐浏览器,去 http://www.google.com/搜索"Bath Fitter"。当我看到一堆链接时,我实际上想点击谷歌提供的顶部菜单的一个项目,图像。图片位于地图视频新闻旁边...如何让它点击图像?
下面是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumHelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = null;
try
{
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
searchInput.FindElement(By.Name("Images"));
searchInput.Click();
driver.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception ****" + e.ToString());
}
}
}
}
更具体地说,您还可以从顶部导航编写指向的选择器。这是XPath。
.//*[@id='hdtb_msb']//a[.='Images']
试试这个;
driver.FindElement(By.XPath(".//*[@id='hdtb_msb']//a[.='Images']"));
编辑:即使上面的选择器是正确的,您的代码也无法正常工作,因为第二页加载时间太长。在那里,您需要等待元素处于就绪状态,并且需要隐式等待。更改您的 try 块中的代码并替换为我的并尝试
driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("gbqfq"));
searchInput.SendKeys("Bath Fitter");
searchInput.SendKeys(Keys.Enter);
//this is the magic
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
By byImage = By.XPath(".//*[@id='top_nav']//a[.='Images']");
IWebElement imagElement =
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byImage));
imagElement.Click();
尝试这样的事情...
IList<IWebElement> links = driver.FindElements(By.TagName("a"));
links.First(element => element.Text == "Images").Click();