Selenium C#中Try Catch块异常跳转问题求助
Selenium C#自动化异常问题求助
我在使用Selenium C#进行网站自动化时遇到异常:尽管已正确设置元素的XPath等属性名称,且配置了WebDriverWait等待函数,代码仍直接从Try块跳转到Catch块,反复触发Captcha()函数执行。相关代码如下:
public void scrapping() { WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(15)); int retryCount = 0; const int maxRetries = 3; for (int i = 0; i < currentPage; i++) { try { IWebElement chkbox = wait1.Until(ExpectedConditions.ElementToBeClickable(By.Id("checkboxCol"))); wait1.Until(ExpectedConditions.ElementToBeClickable(chkbox)).Click(); IWebElement next = wait1.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*[@id=\"searchResults\"]/div[1]/div/div[1]/div[2]/div[3]"))); wait1.Until(ExpectedConditions.ElementToBeClickable(next)).Click(); wait1.Until(ExpectedConditions.StalenessOf(next)); wait1.Until(ExpectedConditions.StalenessOf(chkbox)); retryCount = 0; // Reset retry count on success } catch (WebDriverException ex) when (ex.Message.Contains("disconnected")) { Console.WriteLine("Browser was manually closed. Aborting the test."); Assert.Fail("Browser was manually closed."); } catch (Exception ex) { retryCount++; if (retryCount >= maxRetries) { Assert.Fail("Failed after multiple retries: " + ex.Message); } else { Console.WriteLine("Captcha detected or unexpected error. Retrying..."); Captcha(); i--; // Retry the current iteration } } } } public void Captcha() { string API = "TBD"; Console.WriteLine("Solving captcha..."); TwoCaptcha solver = new TwoCaptcha(""); // API goes here HCaptcha captcha = new HCaptcha(); captcha.SetSiteKey("eTBD"); captcha.SetUrl("https://2captcha.com/demo/hcaptcha"); try { solver.Solve(captcha).Wait(); Console.WriteLine("Captcha solved: " + captcha.Code); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript($"document.getElementsByName('h-captcha-response')[0].value = '{captcha.Code}';"); } catch (AggregateException e) { Console.WriteLine("Error occurred: " + e.InnerExceptions.First().Message); } }
排查与解决建议
- 明确异常根源:在Catch块中打印完整异常堆栈(
Console.WriteLine(ex.ToString());),不要默认归因为验证码,确认是元素定位失败、超时还是真的触发了验证码拦截。 - 验证元素定位稳定性:
- 检查
checkboxCol是否为页面唯一ID,部分网站会动态生成ID,建议结合类名、文本等属性组合定位; - 当前XPath依赖页面层级结构,若页面布局变化会直接失效,改用更稳定的定位方式,比如包含按钮文本的XPath:
//div[contains(text(), '下一页')](根据实际按钮文本调整)。
- 检查
- 优化等待逻辑:
- 获取到
chkbox和next元素后,直接调用Click()即可,无需再次用ElementToBeClickable等待,因为首次Until已经确保元素可点击; StalenessOf等待需确认页面跳转后目标元素确实被销毁,若页面未完全跳转,会导致超时触发异常。
- 获取到
- 修正验证码处理逻辑:
- 将Captcha()中的
captcha.SetUrl替换为你实际操作的目标网站URL,而非2Captcha的演示地址; - 注入验证码响应值后,部分网站需要触发验证回调,比如执行
js.ExecuteScript("document.querySelector('.h-captcha').dispatchEvent(new Event('change'));")(根据网站实际验证机制调整); - 确认TwoCaptcha的API密钥已正确填写,且账户有可用余额。
- 将Captcha()中的
- 调整重试逻辑:
- 重试前建议刷新页面(
driver.Navigate().Refresh();),确保页面回到初始状态,避免因页面残留异常导致重复失败; - 增加重试间隔,比如
Thread.Sleep(2000);,避免短时间内重复请求触发更严格的反爬机制。
- 重试前建议刷新页面(
内容的提问来源于stack exchange,提问作者Munkhtuvshin Lkhadorj
相关产品推荐
相关产品推荐

