我将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);这不是一个好的解决方案。
感谢。
答案 0 :(得分:4)
对于你的&#34;显式等待:&#34;选项,我认为正确的顺序应该是:
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之前等待页面完全加载。
答案 1 :(得分: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/"));
答案 2 :(得分:1)
尝试这样的事情:
try (
ExpectedConditions.presenceOfElementLocatedBy
ExpectedConditions.visibilityOfElementLocatedBy
) catch error if both conditions are not met