You need to enable JavaScript to run this app. 使用C# Selenium如何通过XPath点击「Practice Form」链接实现跳转
优惠活动
大模型
产品
解决方案
定价
更多

使用C# Selenium如何通过XPath点击「Practice Form」链接实现跳转

C# Selenium 实现要求的页面跳转流程

核心可运行代码

// 提前通过NuGet安装依赖包:Selenium.WebDriver、Selenium.WebDriver.ChromeDriver、DotNetSeleniumExtras.WaitHelpers
IWebDriver driver = new ChromeDriver();
// 配置显式等待最长超时时间为10秒
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

try
{
    // 导航到题目指定的基础操作页面
    driver.Navigate().GoToUrl("https://demoqa.com/forms");

    // 通过XPath匹配Practice Form链接,等待元素可点击后执行点击
    IWebElement practiceFormLink = wait.Until(
        SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(
            By.XPath("//a[text()='Practice Form']"))
    );
    practiceFormLink.Click();

    // 可选校验:确认已成功跳转到目标表单页面
    wait.Until(d => d.Url.Contains("automation-practice-form"));
}
finally
{
    // 测试结束后释放浏览器资源
    driver.Quit();
}

落地注意事项

  • 本次使用的XPath直接匹配链接的可见文本,不依赖页面动态生成的class、id属性,后续前端调整元素样式也不会导致定位失效
  • 必须使用显式等待替代Thread.Sleep类强制休眠逻辑,避免页面加载节奏不稳定导致的偶发定位失败
  • 流程严格符合题目约束:全程没有直接导航到最终练习表单URL的操作,跳转完全通过元素点击完成

内容的提问来源于stack exchange,提问作者farrukhmask

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 03:57:03