简体   繁体   中英

How to Get the text from an element through Selenium and C#

How can i Get the 2.22 Number From this Codes?

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

I had Tried This Code But it Does Not worked! Note: The XPATH that I given is For <div class="col bold h-col-1 c-green">2.22</div> tag!

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);

You can first try to use relative xpath to find element as //div[contains(@class, 'h-col-1')]

Then try to get the value using

  1. Text (element.Text)
  2. Get Attribute (element.GetAttribute("value"))

To extract the text 2.22 , as the element is a dynamic element, you may use WebDriverwait with element to be visible and you can use either of the following solution:

  • 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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM