【问题标题】:How to know a URL is existing using Selenium WebDriver using C#?如何使用 C# 使用 Selenium WebDriver 知道 URL 是否存在?
【发布时间】:2019-04-21 16:19:52
【问题描述】:

在我的应用程序中,我存储了一个 URL 列表,并且只存储了具有现有 URL 的产品(即不是任何 404 或找不到页面或损坏的 URL)。

我想在我的页面中查看,然后导航到该页面。现在我需要使用 Selenium 和 C# 中的 WebDriver 获取检查给定 URL 是否存在的代码。

【问题讨论】:

  • 为什么不使用 WebClient.DownloadString(url) 来做到这一点?没有必要涉及低效的硒。
  • 如何使用它?我怎么知道一个页面是否存在?使用此代码。
  • 如果你请求的页面不存在(404),该方法会抛出一个WebException,见MSDN这里:docs.microsoft.com/en-us/dotnet/api/…
  • 尝试{ new WebClient().DownloadString(url); } 捕捉 (WebException ex) { ... }
  • 实际上WebException是由WebClient类底层的WebRequest对象抛出的,所以你也可以直接使用WebRequest类。你可以google一下如何使用这个类。

标签: c# selenium selenium-webdriver


【解决方案1】:
string urlFraction = "/myfolder/some.html";
double seconds = 10;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
bool wellTheAddressBarChanged = wait.Until(ExpectedConditions.UrlContains(urlFraction));

// TODO: Give IE11 special treatment here.
bool thePageActuallyLoaded = wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2012-03-20
    • 2014-01-05
    • 2019-01-26
    • 1970-01-01
    • 2013-10-30
    相关资源
    最近更新 更多