【问题标题】:Selenium: Find the base UrlSelenium:查找基本 URL
【发布时间】:2013-08-30 04:36:27
【问题描述】:

我在不同的机器上使用 Selenium 来自动测试 MVC Web 应用程序。

我的问题是我无法获取每台机器的基本 url。

我可以使用以下代码获取当前网址:

IWebDriver driver = new FirefoxDriver();
string currentUrl = driver.Url;

但是当我需要导航到不同的页面时,这无济于事。

理想情况下,我可以使用以下内容导航到不同的页面:

driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
driver.Navigate().GoToUrl(baseUrl+ "/Home");

我使用的一种可能的解决方法是:

string baseUrl = currentUrl.Remove(22); //remove everything from the current url but the base url
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");

有没有更好的方法可以做到这一点??

【问题讨论】:

  • 只是为了确保我遵循这一点。示例:给定http://www.google.com/something ...而您特别地只想要http://www.google.com 部分?
  • 当我运行应用程序时,它会转到诸如localhost:12345/Login 之类的URL(这将因机器而异),然后我希望驱动程序转到诸如localhost:12345/Feedback 之类的页面。所以我只想要localhost:12345 部分,因为我无法在我的代码中硬编码指向它的链接,因为它在每台机器上都会有所不同。

标签: c# url selenium


【解决方案1】:

解决此问题的最佳方法是创建 URL 的 Uri 实例。

这是因为 .NET 中的 Uri class 已经有代码可以完全为您执行此操作,因此您应该使用它。我会选择类似(未经测试的代码):

string url = driver.Url; // get the current URL (full)
Uri currentUri = new Uri(url); // create a Uri instance of it
string baseUrl = currentUri.Authority; // just get the "base" bit of the URL
driver.Navigate().GoToUrl(baseUrl + "/Feedback"); 

基本上,您在 Uri 类中的 Authority property 之后。

请注意,有一个属性可以做类似的事情,称为Host,但这不包括您的站点所包含的端口号。不过要记住这一点。

【讨论】:

    【解决方案2】:

    取出driver.Url,将其放入新的System.Uri,然后使用myUri.GetLeftPart(System.UriPartial.Authority)

    如果您的基本 URL 是 http://localhost:12345/Login,这将返回您 http://localhost:12345

    【讨论】:

      【解决方案3】:

      试试这个取自answer的正则表达式。

      String baseUrl;
      Pattern p = Pattern.compile("^(([a-zA-Z]+://)?[a-zA-Z0-9.-]+\\.[a-zA-Z]+(:\d+)?/");
      Matcher m = p.matcher(str); 
      if (m.matches())
          baseUrl = m.group(1);
      

      【讨论】:

        猜你喜欢
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 2022-07-11
        • 1970-01-01
        相关资源
        最近更新 更多