简体   繁体   中英

C# selenium unable to find an element

I'm new in C# and Selenium then I apologize in advance for my trivial question. I'm trying to automate the reading of numbers in a counter in a web page, below is the portion of HTML that concerns the above counter:

<div class="row counter_container_div" xpath="1">
 <h1 class="counter"> 
   <span id="multiplier_first_digit" style="">0</span> 
   <span id="multiplier_second_digit">9</span> 
   <span id="multiplier_third_digit" style="">4</span> 
   <span id="multiplier_fourth_digit" style="">2</span> 
   <span id="multiplier_fifth_digit" class="margin_right0">7</span>
 </h1>
</div>

This is instead the piece of C # code to try to find the third digit of the counter:

var digit = driver.FindElement(By.XPath("//span[@id='multiplier_third_digit']")).ToString();
        Console.WriteLine(digit);
        Console.Read();

The result that the console returns to me is as follows:

Element (id = 0.9456097574416866-3)

Why? How do I get the result that is present in the HTML code that would be 4? Thanks for all your help. See you soon

您可以尝试以下代码获取文本

var digit = driver.FindElement(By.XPath("//span[@id='multiplier_third_digit']")).Text;

You want to use the Text property. Using ToString() is returning info of the webelement object.

Also, as a general Selenium suggestion, I would recommend using the By.Id selector in this case. Your xpath will work, but using ID is easier to both read and write, and it'll technically be processed a bit faster by WebDriver. So, try this:

var digit = driver.FindElement(By.Id("multiplier_third_digit")).Text;

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