我当前正在循环中遇到问题,基本上,当我打电话时,第一个过程可以正常工作-
代码示例:
public static void Search()
{
var Lines = File.ReadLines(@"in.txt").Take(1000).ToList();
var query = string.Join(Environment.NewLine, Lines);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(300));
IWebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("search")));
if (driver.FindElements(By.Name("search")).Count != 0)
{
driver.FindElement(By.Name("search")).SendKeys(query);
System.Threading.Thread.Sleep(2000);
driver.FindElement(By.Name("submitbtn")).Click();
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Getting Results");
if (driver.FindElements(By.CssSelector("tbody")).Count != 0)
{
Results();
}
}
}
public static void Results()
{
try
{
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
if (driver.FindElements(By.TagName("result")).Count != 0)
{
var element2 = driver.FindElements(By.CssSelector("text"));
foreach (var text in element2)
{
var data = text.GetAttribute("outerHTML");
System.IO.File.AppendAllText("output.txt", data + Environment.NewLine);
}
driver.Navigate().Refresh();
Search();
}
else
{
Console.WriteLine("No results");
driver.Navigate().Refresh();
Search();
}
}
catch
{
Console.WriteLine("Failed to get results");
driver.Close();
Load();
}
}
但返回Search()
第二次尝试,在结果中称为
Search();
成功处理Results();
在第二个搜索过程中,Results()捕获异常引发,即
Failed to get results
但是,当我调用Search()时,Results()函数未处于处理过程中:S,所以我的结论是我从未退出过Results,它仍在处理中,并且在找不到元素30秒钟后引发了异常,但是如何再次调用Search()进行第二次尝试并退出Results()?
答案 0 :(得分:0)
我认为这两行引发异常:
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
从我的角度来看,您已经不需要它们了,
if (driver.FindElements(By.TagName("result")).Count != 0)
如果不确定,结果将快速显示在DOM
中,则可以使用try/catch
块添加暂停或环绕,如下所示:
try {
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement element1 = wait1.Until(ExpectedConditions.ElementToBeClickable(By.TagName("result")));
}catch {
Console.WriteLine("No results");
}
if (driver.FindElements(By.TagName("result")).Count != 0)
PS: 我不确定您是否需要ExpectedConditions.ElementToBeClickable
,因为您没有单击该元素。例如,您可以使用ExpectedConditions.ElementToBeVisible
。