首页 > 解决方案 > 如何使用 C# selenium 绕过这层 javascript?

问题描述

以下是我尝试使用的源代码。我曾尝试使用以下方法:

driver.FindElement(By.XPath("//span[@data-bind = 'text: Caption']")).Click();
driver.FindElement((By.XPath("//*[contains(text(),'document')]"))).Click();

我在项目中使用的所有传统硒方法都找不到任何东西。

<div class="caption" data-bind="css: { 'doc-downloader-wrapper': $data.IsDocument() }">
  <a data-bind="css: { 'protected': IsProtectedDocument(), 'doc-downloader': $data.IsDocument(), 'no-       details': !$data.HasDetails() }, attr: { href: Link, target: $data.IsLinkDocument() ? '_blank' :         '_self' }">
    <span data-bind="text: Caption"></span>
  </a>
</div>

标签: c#selenium-webdriverxpathwebdriverwait

解决方案


所需元素是动态元素,因此您必须为所需的ElementToBeClickable诱导WebDriverWait ,并且您可以使用以下任一定位器策略作为解决方案:

  • CssSelector

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div.caption[data-bind*='doc-downloader-wrapper']>a[data-bind*='IsProtectedDocument']>span[data-bind$='Caption']"))).Click();
    
  • XPath

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@class='caption' and contains(@data-bind, 'doc-downloader-wrapper')]/a[contains(@data-bind, 'IsProtectedDocument')]/span[contains(@data-bind, 'Caption')]"))).Click();
    

推荐阅读