【问题标题】:Unable to select the last li element within a ul using Selenium Webdriver for C#无法使用 Selenium Webdriver for C# 选择 ul 中的最后一个 li 元素
【发布时间】:2021-10-14 15:12:42
【问题描述】:

我有一个如下所示的代码块,我想获取位于最后一个按钮元素内的 span 的文本(内部 html;必须为 4)李。

<ul class="xyz">
    <li class="abc">  
        <button aria-current="true" type="button">
            <span>1</span>
        </button>
    </li>
    <li class="abc">  
        <button aria-current="true" type="button">
            <span>2</span>
        </button>
    </li>
    <li class="abc">  
        <button aria-current="true" type="button">
            <span>3</span>
        </button>
    </li>
    <li class="abc">  
        <button aria-current="true" type="button">
            <span>4</span>
        </button>
    </li>
</ul>

当我使用以下代码行时,我得到 "no such element: Unable to locate element: {"method":"xpath","selector":"//ul[@class='xyz' ]/li[last()]/button/span"}"

string text= driver.FindElement(By.XPath("//ul[@class='xyz']/li[last()]/button/span")).Text;

或者,当我使用此代码时,我得到了同样的错误。

string text= driver.FindElement(By.XPath("//ul[@class='xyz']/li[last()]//button//span")).Text;

【问题讨论】:

    标签: c# html selenium-webdriver xpath selenium-chromedriver


    【解决方案1】:

    您使用了错误的 XPath。
    试试这个

    string text= driver.FindElement(By.XPath("(//ul[@class='xyz']//li)[last()]/button/span")).Text;
    
    

    string text= driver.FindElement(By.XPath("(//ul[@class='xyz']//li)[last()]//span")).Text;
    

    【讨论】:

    • 我尝试了你的两个建议,但我仍然得到 no such element: Unable to locate element: {"method":"xpath","selector"....错误。
    • 也许你错过了一些等待/延迟或元素在 iframe 内?
    猜你喜欢
    • 2020-12-19
    • 1970-01-01
    • 2019-08-15
    • 2019-02-05
    • 2021-07-03
    • 2011-03-10
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多