【问题标题】:How to Get the text from an element through Selenium and C#如何通过 Selenium 和 C# 从元素中获取文本
【发布时间】:2019-05-30 00:59:19
【问题描述】:

如何从该代码中获取 2.22 数字?

<div class="crash-row crash-0d54ae895d62d03cfb4bdcb502109630">
    <div class="col bold h-col-1 c-green">2.22</div>
    <div class="col h-col-2">-</div>
    <div class="col h-col-3">-</div>
    <div class="col h-col-4">-</div>
    <div class="col h-col-5">
        <a href="javascript:;" class="show-code">0d54ae895d62d03cfb4bdcb502109630</a>
    </div>
    <div class="col h-col-6">
        <a href="javascript:;" class="show-code">8d76a8fa2b7613de95a7e13852055c77d013f441952a231c47ca0872bcdd64df</a>
    </div>
        <div class="clear">
    </div>
</div>

我曾尝试过此代码,但它不起作用! 注意:我给出的 XPATH 是 For &lt;div class="col bold h-col-1 c-green"&gt;2.22&lt;/div&gt; 标签!

Console.Write(driver.FindElement(By.XPath("/html/body/div[2]/div[5]/div[2]/div[5]/div[3]/div[2]/div[2]/div[2]")).Text);

【问题讨论】:

  • 试试 CSS 选择器 .crash-row &gt; .c-green。还分享更多关于“但它不起作用!”的细节

标签: c# selenium xpath css-selectors webdriverwait


【解决方案1】:

您可以先尝试使用相对 xpath 来查找元素 //div[contains(@class, 'h-col-1')]

然后尝试使用获取值

  1. 文本 (element.Text)
  2. 获取属性 (element.GetAttribute("value"))

【讨论】:

    【解决方案2】:

    提取文本2.22,由于元素是动态元素,你可以使用WebDriverwaitelement to be visible,你可以使用以下任一解决方案:

    • CssSelector

      new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div.crash-row > div.c-green"))).GetAttribute("innerHTML");
      
    • XPath

      new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[contains(@class, 'crash-row')]/div[contains(@class, 'c-green')]"))).GetAttribute("innerHTML");
      

    【讨论】:

      猜你喜欢
      • 2015-05-10
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2019-02-16
      • 2018-11-08
      • 1970-01-01
      相关资源
      最近更新 更多