nella mia applicazione UWP ho bisogno di prendere il titolo e il link del primo video in una pagina di YouTube da HtmlAgilityPack, ma il risultato è il seguente, e il valore di title e href non è mostrato.
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]]">
Questo è il codice
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;
Utilizzare WebView
anziché HtmlWeb
per ottenere l'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;" });
}
Il primo video era nel secondo indice. Quindi utilizzare SelectNodes
e selezionare il secondo indice
HtmlDocument htmlDoc = web.Load(siteHtML );
string result = htmlDoc.DocumentNode.SelectNodes("//div/div/div/div/h3/a")[1].OuterHtml;
Ecco il codice finale
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;
}