gpt4 book ai didi

c# - 使用 AngleSharp 获取和下载图片

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:12 24 4
gpt4 key购买 nike

我开始在一个项目中使用 Anglesharp,我不仅需要获取和下载 HTML,还需要获取和下载文档的图像。我知道在 Document 对象中有一个名为 Images 的属性,但显然它并没有得到所有这些,我在 YouTube 页面上进行了测试并且只得到了一个(重复几次)。例如,我想获取当前视频的缩略图,这似乎在 <meta> 中。标签。更准确地说,图像存储在这种标签中:

<meta content="https://i.ytimg.com/vi/hW-kDv1WcQM/hqdefault.jpg" property="og:image">

所以我想知道是否有一种方法可以选择页面内任何图像的所有节点/url,而不管使用的是什么标签。我认为 QuerySelectorAll 在这种情况下不起作用,因为它只选择一种类型的节点。您可以尝试在 github 上找到的示例代码来验证(我刚刚更改了 YouTube 的 url,以及选择器 :D):

// 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://www.youtube.com/watch?v=hW-kDv1WcQM&feature=youtu.be";
// 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 = "img";
// 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);

哦,当然,你也可以添加这个来检查 Image 属性没有得到视频缩略图:

var Images = document.Images.Select(sl=> sl.Source).Distinct().ToList();

还有其他方法可以根据URL内容选择节点吗? (比如所有以“.jpg”或“.png”等结尾的网址)

最佳答案

您可以使用 LINQ API 获取页面中包含图像 URL 的所有属性,如下所示:

.....
var document = await BrowsingContext.New(config).OpenAsync(address);

//list all image file extension here :
var fileExtensions = new string[] { ".jpg", ".png" };

//find all attribute in any element...
//where the value ends with one of the listed file extension
var result = from element in document.All
from attribute in element.Attributes
where fileExtensions.Any(e => attribute.Value.EndsWith(e))
select attribute;

foreach (var item in result)
{
Console.WriteLine(item.Value);
}

关于c# - 使用 AngleSharp 获取和下载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36023919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com