C#/Selenium - 使用 contains() 找不到 XPath 文本

C# / Selenium - failing to find XPath text using contains()

我有 html 个我希望使用 Selenium 单击的元素:

<a class="epi-navigation-global_user_settings_shell_search " href="DatabaseJob.aspx?pluginId=20">
                                            Importer obligationsliste
                                        </a>

使用以下 xpath:/html/body/form/div[4]/div[1]/div/ul/li[2]/ul/li[19]/a

我尝试通过以下表达式单击包含文本 "Importer obligationsliste" 的元素:

var obligationButton = By.XPath("//a[contains(text(), 'Importer')]");
wait.Until(ExpectedConditions.ElementToBeClickable(obligationButton)).Click();

但从未找到该元素。我也试过完整的字符串 Importer obligationsliste 无济于事。 没有找到元素的任何想法?我怀疑它与文本周围的空格有关,但 contains() 也应该能够找到子字符串。

请转至 https://www.w3schools.com/xml/xpath_intro.asp 并阅读有关编写 xpath 的内容。从 Chrome 抓取路径是你能做的最糟糕的事情。这些路径需要更长的时间才能找到并且非常脆弱。在开发更改中添加 div、ul 或 li,您的路径将会中断。

如果它不在 iframe 中,请尝试以下操作:

//a[contains(text(), 'Importer obligationsliste')]
//a[normalize-space()='Importer obligationsliste']

文本 Importer obligationsliste 有很多前导和尾随空格。因此,对于元素上的 Click(),您必须为所需的 ElementToBeClickable() 引入 WebDriverWait,并且您可以使用以下任一方法 :

  • XPathcontains() 一起用于文本 进口商义务清单:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[contains(., 'Importer obligationsliste')]"))).Click();
    
  • XPathnormalize-space() 用于文本 进口商义务清单:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[normalize-space()='Importer obligationsliste']"))).Click();
    
  • 使用 XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//a[@class='epi-navigation-global_user_settings_shell_search ' and starts-with(@href, 'DatabaseJob')]"))).Click();
    
  • 使用 PartialLinkText:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.PartialLinkText("Importer obligationsliste"))).Click();
    
  • 使用 CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("a.epi-navigation-global_user_settings_shell_search[href^='DatabaseJob']"))).Click();