6

我将 Selenium 与 Phantomjs 一起使用,并希望在页面完全加载后获取页面内容。

我试过http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp但它似乎不适用于 phantomjs

显式等待:

using (IWebDriver driver = new PhantomJSDriver())
{
    IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

    driver.Navigate().GoToUrl(url);

    content = driver.PageSource;

    driver.Quit();
}

另一个测试:

using (IWebDriver driver = new PhantomJSDriver())
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

    driver.Url = url;

    IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
        {
            return d.FindElement(By.Id("footer")); // failed because it's not yet loaded full content 
        });

    content = driver.PageSource;
}

或隐式等待:

using (IWebDriver driver = new PhantomJSDriver())
{
    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
    driver.Navigate().GoToUrl(url);

    content = driver.PageSource;

    driver.Quit();
}

内容还很欠缺。唯一的方法是把 Thread.Sleep(waitTime); 这不是一个好的解决方案。

谢谢。

4

3 回答 3

4

对于您的“显式等待:”选项,我认为正确的顺序应该是:

1)通过以下方式导航到目标网址:

driver.Navigate().GoToUrl(url);

2)等到目标网址完全加载

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

这样,下一行将在读取 PageSource 之前等待页面完全加载。

于 2017-03-17T09:11:19.733 回答
3

我创建了一个扩展方法。在这种方法中,您可以输入您的条件。

  public static bool WaitUntil(this IWebDriver driver, Func<IWebDriver, bool> expression, int timeOutSeconds = 10)
    {

        TimeSpan timeSpent = new TimeSpan();

        bool result = false;
        while (timeSpent.TotalSeconds < timeOutSeconds)
        {

            result = expression.Invoke(driver);

            if (result == true)
            {
                break;
            }
            Thread.Sleep(timeSleepingSpan);
            timeSpent = timeSpent.Add(new TimeSpan(0, 0, 0, 0, timeWaitingSpan));

        }
        return result;

    }

喜欢

       driver.WaitUntil(d => d.Url.Equals("https://www.meusite.com/"));
于 2014-09-09T12:57:45.647 回答
1

尝试这样的事情:

try (
  ExpectedConditions.presenceOfElementLocatedBy
  ExpectedConditions.visibilityOfElementLocatedBy
) catch error if both conditions are not met
于 2014-04-08T14:46:36.283 回答