【问题标题】:Getting wrong text value when using Xpath locator使用 Xpath 定位器时获取错误的文本值
【发布时间】:2021-11-12 17:24:13
【问题描述】:

我目前正在学习 Selenium,并获得了一个要创建的测试用例,使用 store.steampowered.com/search/?filter=topsellers 作为测试站点。 我需要获取复选框“Action”附近的数字,如@9​​87654321@

这是描述此特定复选框的页面代码的一部分:

<div class="tab_filter_control_row " data-param="tags" data-value="19" data-loc="Action" data-clientside="0">
    <span class="tab_filter_control tab_filter_control_include " data-param="tags" data-value="19" data-loc="Action" data-clientside="0" data-gpfocus="item">
        <span>
                <span class="tab_filter_control_checkbox"></span>
                <span class="tab_filter_control_label">Action</span>
                <span class="tab_filter_control_count" style="">30</span>
        </span>
    </span>
                <span class="tab_filter_control_not " data-param="untags" data-value="19" data-icon="https://store.akamai.steamstatic.com/public/images/search_crouton_not.svg" data-loc="Action" data-clientside="0" data-tooltip-text="Exclude results with this tag" data-gpfocus="item"><img src="https://store.akamai.steamstatic.com/public/images/search_checkbox_not.svg" width="16px" height="16px"></span>
        </div>

为此,我编写了这个 XPath 定位器://span[@data-value='19']//*[@class='tab_filter_control_count']。但是当我做这样的事情时:

string str = driver.FindElement(By.XPath("//span[@data-value='19']//*[@class='tab_filter_control_count']"));

出于某种原因,我会得到“1 635”,而不是“30”。我尝试使用不同的 XPath 获取文本,//div[@data-collapse-name='tags']//*[@data-value='19'],但结果会是“行动 1635”。

也许有人会解释 30 如何变成 1 635,以及我如何才能得到正确的数字。

【问题讨论】:

  • 你知道 steam 提供了一个 API 吗? steamcommunity.com/dev - 似乎比尝试解析 HTML 更容易。
  • 我受限于测试用例的要求,只能使用特定的编程语言、IDE 等。我会研究这个,但我确信对于这个小部分有更简单的解决方案整个测试用例比使用新的 API。

标签: c# selenium-webdriver xpath webdriverwait getattribute


【解决方案1】:

要提取标签Action旁边的文本30,您可以使用以下Locator Strategy

  • 使用xpathText属性:

    Console.WriteLine(driver.FindElement(By.XPath("//span[text()='Action']//following::span[1]")).Text);
    

理想情况下,您必须为所需的ElementIsVisible 诱导WebDriverWait,您可以使用以下Locator Strategy

  • 使用 xpathGetAttribute():

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//span[text()='Action']//following::span[1]"))).GetAttribute("innerHTML"));
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2015-11-21
    相关资源
    最近更新 更多