C#Selenium XPATH单击基于跨度文本的输入

时间:2019-09-17 14:11:58

标签: c# selenium xpath css-selectors webdriverwait

我试图单击一个输入按钮,其主要标识符是动态创建的。因此,我试图根据其后的跨度信息单击它。

<span id="DYNAMIC" class="a-button a-button-primary pmts-button-input apx-compact-continue-action pmts-portal-component pmts-portal-components-DYNAMIC primary-action-button">
<span class="a-button-inner">
    <input data-pmts-component-id="DYNAMIC" class="a-button-input a-button-text" type="submit" aria-labelledby="DYNAMIC">
        <span id="DYNAMIC" class="a-button-text" aria-hidden="true">
            <span>Use this payment method</span>
        </span>
</span>

我在DYNAMIC中输入了动态创建的ID,而不是输入值。以下是我认为是我尝试过的许多事情的最好版本,但是我仍然无法完成任务。

var btnPaymentMethod = driver.FindElement(By.XPath("//input[normalize-space(.//span)='Use this payment method']"));
btnPaymentMethod.Click();

4 个答案:

答案 0 :(得分:3)

要单击参考跨度标签的输入按钮。请在xpath下使用。

//span[text()='Use this payment method']/preceding::input[1]

尝试以下代码。

var btnPaymentMethod = driver.FindElement(By.XPath("//span[text()='Use this payment method']/preceding::input[1]"));
btnPaymentMethod.Click();

答案 1 :(得分:0)

尝试这个xpath,

var btnPaymentMethod = driver.FindElement(By.XPath("//*[contains(@span,'Use this payment method')]"));
btnPaymentMethod.Click();

答案 2 :(得分:0)

要在文本为使用此付款方式的元素上click(),必须为所需的ElementToBeClickable()引入 WebDriverWait ,并且您可以使用以下Locator Strategies之一:

  • cssSelector

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("span.a-button-inner span.a-button-text>span"))).Click();
    
  • xpath

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//span[@class='a-button-text']/span[text()='Use this payment method']"))).Click();
    

答案 3 :(得分:0)

以下xpath也会为您找到输入元素:

"//span[text() = 'Use this payment method']/../parent::span/input"

"//span[contains(text(), 'Use this payment method')]/../parent::span/input"