簡體   English   中英

用AngleSharp解析

[英]Parsing with AngleSharp

編寫程序以使用AngleSharp解析來自一個網站的某些數據。 不幸的是,我沒有找到任何文檔,這使理解變得非常困難。

  1. 如何使用QuerySelectorAll只獲取鏈接? 我現在得到的所有內容<a ...>...</a>帶有Name of article

<a href="http://kinnisvaraportaal-kv-ee.postimees.ee/muua-odra-tanaval-kesklinnas-valmiv-suur-ja-avar-k-2904668.html?nr=1&amp;search_key=69ec78d9b1758eb34c58cf8088c96d10" class="object-title-a text-truncate">1. Name of artucle</a>

我現在使用的方法:

var items = document.QuerySelectorAll("a").Where(item => item.ClassName != null && item.ClassName.Contains("object-title-a text-truncate"));
  1. 在前面的示例中,我還使用了ClassName.Contains(“ object-name”),但是如果處理表單元格,則沒有任何類。 據我了解解析正確的元素,也許我也必須使用有關父級的一些信息。 所以這是一個問題,如何從表格單元中獲取“ 4”值?

.... <th class="strong">Room</th> <td>4</td> ...。

關於第一個問題。 這是您可以提取鏈接地址的示例。 這是另一個與Stackoveflow相關的帖子的鏈接

var source = @"<a href='http://kinnisvaraportaal-kv-ee.postimees.ee/muua-odra-tanaval-kesklinnas-valmiv-suur-ja-avar-k-2904668.html?nr=1&amp;search_key=69ec78d9b1758eb34c58cf8088c96d10' class='object-title-a text-truncate'>1. Name of artucle</a>";
var parser = new HtmlParser();
var doc = parser.Parse(source);

var selector = "a";

var menuItems = doc.QuerySelectorAll(selector).OfType<IHtmlAnchorElement>();

foreach (var i in menuItems)
{
    Console.WriteLine(i.Href);
}

對於第二個問題,您可以檢查文檔中的示例,這里是鏈接 ,下面是代碼示例:

// Setup the configuration to support document loading
var config = Configuration.Default.WithDefaultLoader();
// Load the names of all The Big Bang Theory episodes from Wikipedia
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
// Asynchronously get the document in a new context using the configuration
var document = await BrowsingContext.New(config).OpenAsync(address);
// This CSS selector gets the desired content
var cellSelector = "tr.vevent td:nth-child(3)";
// Perform the query to get all cells with the content
var cells = document.QuerySelectorAll(cellSelector);
// We are only interested in the text - select it with LINQ
var titles = cells.Select(m => m.TextContent);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM