如何通过硒按照html单击按钮?



我正在尝试使用硒查找并单击此按钮:

<button class="orangeButton nextStep js-submitForm js-pop" data-href="/user/welcome/subscribe">Take me to my Subscriptions</button>

但是,没有id并且类名太长,所以我想使用xpath。但是,我不明白如何使用它。

当前代码:

driver.FindElement(By.XPath("//button[@class='orangeButton nextStep js-submitForm js-pop'")).Click();

但这失败了,因为不是有效的 xpath 参数

试一试。 不能将空格分隔的类视为一个类字符串。 空间意味着它是一个不同的类,你必须单独对待每个类。

driver.FindElement(By.Xpath("//button[contains(@class, 'orangeButton') and contains(@class, 'nextStep') and contains(@class, 'js-submitForm') and contains(@class, 'js-pop')]"));

无需使用所有类来定位元素,只需使用那些使元素唯一的类。

通过 css:

driver.FindElement(By.CssSelector("button.nextStep"));
driver.FindElement(By.CssSelector("button.orangeButton.nextStep"));
driver.FindElement(By.CssSelector("button.orangeButton.nextStep.js-submitForm.js-pop"));

按路径和类:

driver.FindElement(By.XPath("//button[contains(@class,'orangeButton) and contains(@class,'nextStep)'"));

通过路径和文本:

driver.FindElement(By.Xpath("//button[normalize-space(., 'Take me to my Subscriptions')"));

根据您共享的 HTML 所需元素是启用 JavaScript 的元素,因此您必须诱导WebDriverWait该元素可单击,您可以使用以下任一解决方案:

  • xpath

    new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//button[@class='orangeButton nextStep js-submitForm js-pop' and contains(@data-href,'subscribe')][contains(.,'Take me to my Subscriptions')]"))).Click();
    
  • cssSelector

    new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.orangeButton.nextStep.js-submitForm.js-pop[data-href$='subscribe']"))).Click();
    

没有。 您可以通过 XPath 尝试的方法,只需尝试以下 XPath 表达式:

"//button[@class='orangeButton nextStep js-submitForm js-pop']"
"//*[@class='orangeButton nextStep js-submitForm js-pop']"
"//*[contains(@class,'orangeButton nextStep js-submitForm js-pop')]"
"//*[contains(@class,'orangeButton')]" // contains() can accept partial text as well

还要检查以下内容(是否有效(

"//*[contains(@data-href,'/user/welcome/subscribe')]"
"//*[contains(@data-href,'subscribe')]"

通过使用 AND 和/或 OR

"//*[@class='orangeButton nextStep js-submitForm js-pop' and @data-href='/user/welcome/subscribe']"
"//*[@class='orangeButton nextStep js-submitForm js-pop' OR @data-href='/user/welcome/subscribe']"