parse htmldocument htmlagilitypack agility c# html-agility-pack web-scraping

c# - htmldocument - ¿Alguien puede explicar este fragmento de código HtmlAgilityPack?



htmlagilitypack xpath (2)

En términos de HTML Agility Pack, "// a" significa "Buscar todas las etiquetas llamadas ''a'' o ''A'' en cualquier lugar del documento". Consulte los documentos de XPATH para obtener una ayuda más general sobre XPATH (independientemente del paquete de agilidad de HTML). Entonces, si el documento se ve así:

<div> <A href="xxx">anchor 1</a> <table ...> <a href="zzz">anchor 2</A> </table> </div>

Obtendrás los dos elementos HTML de anclaje. OuterHtml representa el HTML del nodo, incluido el nodo en sí, mientras que InnerHtml representa solo el contenido HTML del nodo. Entonces, aquí los dos OuterHtml son:

<A href="xxx">anchor 1</a>

y

<a href="zzz">anchor 2</A>

Tenga en cuenta que he especificado ''a'' o ''A'' porque la implementación de HAP tiene cuidado o la insensibilidad a las mayúsculas y minúsculas HTML. Y "// A" dos no funciona de manera predeterminada. Debe especificar las etiquetas con minúsculas.

Hice mi mejor esfuerzo para agregar comentarios a través del código, pero estoy atascado en ciertas partes.

// create a new instance of the HtmlDocument Class called doc 1: HtmlDocument doc = new HtmlDocument(); // the Load method is called here to load the variable result which is html // formatted into a string in a previous code snippet 2: doc.Load(new StringReader(result)); // a new variable called root with datatype HtmlNode is created here. // Im not sure what doc.DocumentNode refers to? 3: HtmlNode root = doc.DocumentNode; 4: // a list is getting constructed here. I haven''t had much experience // with constructing lists yet 5: List<string> anchorTags = new List<string>(); 6: // a foreach loop is used to loop through the html document to // extract html with ''a'' attributes I think.. 7: foreach (HtmlNode link in root.SelectNodes("//a")) 8: { // dont really know whats going on here 9: string att = link.OuterHtml; // dont really know whats going on here too 10: anchorTags.Add(att) 11: }

Levanté esta muestra de código desde aquí . Crédito a Farooq Kaiser


La clave es el método SelectNodes. Esta parte usó XPath para obtener una lista de nodos del HTML que coincida con su consulta.

Aquí es donde aprendí mi XPath: http://www.w3schools.com/xpath/default.asp

Luego, simplemente recorre los nodos que coinciden y obtiene OuterHTML, el código HTML completo que incluye las etiquetas, y las agrega a la lista de cadenas. Una lista es básicamente una matriz, pero más flexible. Si solo deseara los contenidos, y no las etiquetas adjuntas, usaría HtmlNode.InnerHTML o HtmlNode.InnerText.