【问题标题】:Selenium driver.Title returning different values C#Selenium driver.Title 返回不同的值 C#
【发布时间】:2023-03-11 09:00:03
【问题描述】:

在我的程序中,我让驱动程序单击页面并获取其标题并将其放入字符串中。在调试中,我看到 driver.Title 是新页面的标题,但字符串包含上一页的标题。我该如何解决这个问题并将第二页标题分配给字符串?

//Title == "Supreme"
driver.Navigate().GoToUrl(baseURL + "/shop/all");
driver.FindElement(By.XPath(".//*[@id='container']/article[" + num.ToString() + "]/div/a/img")).Click();
//title of this page should be Supreme: Supreme®/Schott® Shearling Bomber - Lime Green

string title = driver.Title;
//returns first title and not title of new page

【问题讨论】:

  • 您需要等待页面加载或使用条件等待标题,如@Guy 建议的。
  • 根本问题是你点击了一个 元素。如果你这样做,Selenium 将立即执行下一行代码,此时下一页还没有加载,你会得到奇怪的结果。如果你可以点击一个 元素,那么 Selenium 默认会等到页面完全加载后再执行下一行代码。
  • @HappyBird 嗨,我已经从 xpath 中删除了 /img,但我的程序似乎没有在等待。我可以看到它导航到下一页,但现在在我的调试中 driver.Title = Supreme(第一页标题),我的字符串 title = null

标签: c# selenium selenium-webdriver webdriver selenium-firefoxdriver


【解决方案1】:

这可能是时间问题,这就是为什么您在较慢的调试中看到正确的值,但在运行脚本时却没有。您可以使用显式等待 ExpectedConditions TitleIsTitleContains 来等待正确的标题

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.TitleIs("Supreme: Supreme®/Schott® Shearling Bomber - Lime Green"));
// or
wait.Until(ExpectedConditions.TitleContains("Shearling Bomber - Lime Green"));

这将等待您给出的条件最多 10 秒。如果标题已更改,它将立即继续,否则您将获得TimeoutException

【讨论】:

  • 我在我的程序中应用了 titleContains 块,但现在它显示我的字符串包含 null,并且似乎根本没有等待
  • driver.Title 也是调试中的正确值
  • 没关系,我在重启 vs 后就可以正常工作了,谢谢!
猜你喜欢
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多