0

编写程序来解析来自一个网站的一些数据,使用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>_

4

1 回答 1

1

关于你的第一个问题。这是一个可以提取链接地址的示例。这是另一个相关的 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);
于 2017-05-17T16:25:57.097 回答