LoneXcoder
LoneXcoder

Reputation: 2163

Selenium - Get elements html rather Text Value

Via that code i have extracted all desired text out of a html document

private void RunThroughSearch(string url)
{
    private IWebDriver driver;
    driver = new FirefoxDriver();
    INavigation nav = driver.Navigate();
    nav.GoToUrl(url);

    var div = driver.FindElement(By.Id("results"));
    var element = driver.FindElements(By.ClassName("sa_wr"));
}

though as i need to refine results of extracted document

Container
    HEADER -> Title of a given block
    Url -> Link to the relevant block
    text -> body of a given block
/Container

as u can see in my code i am able to get the value of the text part as a text value , that was fine, but what if i want to have the value of the container as HTML and not the extracted text ?

<div class="container">
    <div class="Header"> Title...</div>
    <div class="Url"> www.example.co.il</div>
    <div class="ResConent"> bla.. </div>
</div>

so the container is about 10 times in a page i need to extract it's innerHtml .

any ideas ? (using Selenium)

Upvotes: 24

Views: 33797

Answers (3)

Hassan Rahman
Hassan Rahman

Reputation: 5213

I found the solution from SQA-SO

IWebDriver driver;
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("document.getElementById("title").innerHTML = "New text!";");

Upvotes: 0

Oli Wennell
Oli Wennell

Reputation: 866

This seemed to work for me, and is less code:

var element = driver.FindElement(By.ClassName("sa_wr"));
var innerHtml = element.GetAttribute("innerHTML");

Upvotes: 55

Yi Zeng
Yi Zeng

Reputation: 32885

Find the element first, then use IJavaScriptExecutor to get the inner HTML.

var element = driver.FindElements(By.ClassName("sa_wr"));
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
if (js != null) {
    string innerHtml = (string)js.ExecuteScript("return arguments[0].innerHTML;", element);
}

Upvotes: 13

Related Questions