简体   繁体   中英

C# - Extract speciifc div class text using HTMLAgility

I have a code in C# where I want to extract the below value (the text "I want this text" in the HTML code below). I have reformat the HTML code to make it easily readable.

<div class="paste-copy-url" style="margin:0 0 0 0;">
    <h4>My Stats:</h4>
    <div class="line">
        <div class="wrap-input">
            <input onclick="this.select();" value="I want this text" readonly="readonly">
        </div>
    </div>
    <h4>Website Link:</h4>
    <div class="line">
        <div class="wrap-input"><input onclick="this.select();" value="Some value" readonly="readonly">
        </div>
    </div>
</div>

The code I tried (It is giving me the text : "Website Link:"):

var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='paste-copy-url']");

What am I doing wrong? Can I use this approach to get that element (There is only 1 instance of the div class in the page)?

var input = htmlDocument.DocumentNode
           .SelectSingleNode("//div[@class='paste-copy-url']//div[@class='wrap-input']/input");
var yourText = input.Attributes["value"].Value;

You can do it like this:

var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='paste-copy-url']//input");
var value = myvaluetoextract.GetAttributeValue("value", null);

//input means you search for input elements in the div 's subtree, recursively. GetAttributeValue is a helper that will never fail, even if the attribute doesn't exists (in this case if will return the 2nd passed parameter - which is null here)

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