开发者

How to get all the element from HTML who having same class attribute?

开发者 https://www.devze.com 2023-04-08 04:54 出处:网络
I developing one asp.net application in that I using htmlagility dll to get all <div> tags which is same class attributes..

I developing one asp.net application in that I using htmlagility dll to get all <div> tags which is same class attributes..

How to get all elements who have same class from whole html page,

I getting top 1 div who having class='myclass' but in,

my case I want to all div tags who have 'myclass' class.

var vardoc = web.Load("<any website url>"); 
var varmyclass = doc.DocumentNode.SelectSingleNode("//div[@class='myclass']"); 

when I used above method then I getting inner html content of the 'myclass' but in my html contents there are many div tags who have class 'myclass'. I want to get all <div> who have same class using HTMLagility开发者_如何学C or other


Don't select a single node in that case.

You are using SelectSingleNode, which will return only one node.

Use SelectNodes instead:

var varmyclass = doc.DocumentNode.SelectNodes("//div[@class='myclass']");


You're pretty much searching an XML document for these nodes.

First off, you're selecting a single node which will only return 1. You need to use SelectNodes.

example:

var varmyclass = doc.DocumentNode.SelectNodes("//div[@class='myclass']");

Update - Removed my Xpath suggestion as it didn't work as I thought it would...


Two issues, first one is that you should be using SelectNodes() instead as the other answers have pointed out since you want to select multiple nodes.

Also, your XPath is a bit restrictive. It will only get div elements which has only one class, myclass but doesn't include those that have multiple classes. I suspect you want to include those as well. Rather than checking if the class is equal, check if it contains it.

var xpath = "//div[contains(@class,'myclass')]";
var query = doc.DocumentNode.SelectNodes(xpath);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号