简体   繁体   中英

Selenium: How to use findElement(By.cssSelector) to extract text from HTML

Hello I want you to get the text @user ie ( span class="user" ) from Class messenger using driver.FindElementsByCssSelector('');

Because the same code is on the same page, but with a different start div class="messenger

Note: The code cannot be changed on the site

<div class="messenger">
    <div class="two"> 
        <div class="three">  
            <a class="complex" rel="user" href="https://example.com"> 
                <img class="avatar pull-right" src="https://example.co/a.jpg" alt="avatar"> 
            </a>    
        </div> 
        <div class="webs">      
            <a class="link-complex" rel="user" href="afaq"> 
                <b class="link-complex-target">website</b> 
                <span class="user">@user</span> 
            </a>
        </div>
    </div> 
</div>

Thanks,

To extract the text @user so you have to induce WebDriverWait for the desired ElementToBeClickable() and you can use either of the following Locator Strategies :

  • ClassName :

     Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.ClassName("user"))).Text);
  • CssSelector :

     Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//span.user"))).GetAttribute("value"));
  • XPath :

     Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//span[@class='user']"))).GetAttribute("value"));

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