我们巴西人对糟糕的解决方法“Gambiarra”有一个词......嗯......至少他们完成了这项工作......这是我的:
var url = "www.your.url.here"
try {
DRIVER.Navigate().GoToUrl(url);
} catch {
// Here you can freely use the Selenium's By class:
WaitElement(By.Id("element_id_or_class_or_whatever_to_be_waited"), 60);
}
// rest of your application
我的WaitElement(By, int)
工作:
/// <summary>
/// Waits until an element of the type <paramref name="element"/> to show in the screen.
/// </summary>
/// <param name="element">Element to be waited for.</param>
/// <param name="timeout">How long (in seconds) it should be waited for.</param>
/// <returns>
/// False: Never found the element.
/// True: Element found.
/// </returns>
private bool WaitElement(By element, int timeout)
{
try {
Console.WriteLine($" - Waiting for the element {element.ToString()}");
int timesToWait = timeout * 4; // Times to wait for 1/4 of a second.
int waitedTimes = 0; // Times waited.
// This setup timesout at 7 seconds. you can change the code to pass the
do {
waitedTimes++;
if (waitedTimes >= timesToWait) {
Console.WriteLine($" -- Element not found within (" +
$"{(timesToWait * 0.25)} seconds). Canceling section...");
return false;
}
Thread.Sleep(250);
} while (!ExistsElement(element));
Console.WriteLine($" -- Element found. Continuing...");
// Thread.Sleep(1000); // may apply here
return true;
} catch { throw; }
}
在此之后,您可以玩timeout
...
让By
您注意到在页面中最后加载的内容(如 javascript 元素和验证码)记住:它将// rest of your application
在页面完全加载之前开始工作,因此最好将 aThread.Sleep(1000)
放在最后以确保...
另请注意,此方法将在 Selenium 的 60 秒标准超时后调用DRIVER.Navigate().GoToUrl(url);
不是最好的,但是......正如我所说:一个好的gambiarra可以完成工作......