c# - UWP C#中的HtmlAgilityPack Youtube搜索

标签 c# web-scraping youtube uwp html-agility-pack

在我的UWP应用程序中,我需要使用HtmlAgilityPack获得youtube页面中第一个视频的标题和链接,但结果如下所示,并且title和href的值未显示。

id="video-title" 
class="yt-simple-endpoint style-scope ytd-video-renderer" 
aria-label$="[[data.title.accessibility.accessibilityData.label]]" 
href$="[[computeHref_(data.navigationEndpoint)]]" 
title$="[[getSimpleString(data.title)]]" 
data="[[data.navigationEndpoint]]">

这是代码
var html = @"https://www.youtube.com/results?search_query=cado+dalle+nubi+trailer+ita";

HtmlWeb web = new HtmlWeb();
HtmlDocument htmlDoc = web.Load(html);

var node = htmlDoc.DocumentNode.SelectSingleNode("//div/div/div/div/h3/a");
string result = node.OuterHtml;

最佳答案

使用WebView而不是HtmlWeb获取HTML

WebView webView = new WebView();
webView.Navigate(new Uri(@"https://www.youtube.com/results?search_query=cado+dalle+nubi+trailer+ita"));

private async void WebView_NavigationCompletedAsync(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    var siteHtML = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.innerHTML;" });
}

第一个视频在第二个索引中。因此,使用SelectNodes并选择第二个索引
HtmlDocument htmlDoc = web.Load(siteHtML );
string result = htmlDoc.DocumentNode.SelectNodes("//div/div/div/div/h3/a")[1].OuterHtml;

这是最终代码
WebView webView = new WebView();

public void GetFirstVideo(string UrlString)
{
    webView.Navigate(new Uri(UrlString));
    webView.NavigationCompleted -= WebView_NavigationCompletedAsync;  //To avoid multiple subscribe
    webView.NavigationCompleted += WebView_NavigationCompletedAsync;
}

private async void WebView_NavigationCompletedAsync(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    webView.NavigationCompleted -= WebView_NavigationCompletedAsync;  //To stop if there is any re-direct
    var siteHtML = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.innerHTML;" });
    var htmlDocument = new HtmlDocument();
    htmlDocument.LoadHtml(siteHtML);
    var firstVideoTitle = htmlDocument.DocumentNode.SelectNodes("//div/div/div/div/h3/a")[1].OuterHtml;
}

关于c# - UWP C#中的HtmlAgilityPack Youtube搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718681/

相关文章:

c# - 使用相机进行面部检测坐标

c# - 如何使用 Linq To SQL 显示所有记录?

c# - 从数据库中的对象检索数组或列表

python - 我该如何解决; "TypeError: ' WikipediaItem'对象不支持项目分配”

api - youtube Analytics API,指定两个维度

youtube - 如何从 youtube api 获取特定视频的可用字幕列表?

c# - C/C++/C#: how to force repaint of window chrome on windows 7?

javascript - R网络抓取绘图跟踪悬停文本,无需selenium或phantomjs

c - 通过 c/libcurl 使用有效密码访问受密码保护的新闻网站

javascript - 如何使用 api (captions.download