如何通过硒点击html上的按钮?

时间:2018-08-25 19:16:39

标签: c# selenium xpath css-selectors webdriver

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

<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参数

4 个答案:

答案 0 :(得分:0)

尝试一下。您不能将由空格分隔的类视为一个类字符串。空格表示这是一个不同的类,您必须分别对待每个类。

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

答案 1 :(得分:0)

无需使用所有类来查找元素,仅需使用使元素唯一的类即可。

通过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"));

通过xpath和类:

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

通过xpath和文本:

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

答案 2 :(得分:0)

根据您共享的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();
    

答案 3 :(得分:0)

没有。 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']"