Ciao Sto usando il pacchetto di agilità html dai pacchetti di nuget per raschiare una pagina web per ottenere tutti gli url sulla pagina. Il codice è mostrato sotto. Tuttavia, il modo in cui mi viene restituito nell'output i collegamenti sono solo estensioni del sito Web effettivo, ma non il collegamento URL completo come http://www.foo/bar/foobar.com . Tutto quello che otterrò sarà "/ foobar". C'è un modo per ottenere i collegamenti completi dell'url con il codice qui sotto? Grazie!
static void Main(string[] args)
{
List<string> linksToVisit = ParseLinks("https://www.facebook.com");
}
public static List<string> ParseLinks(string email)
{
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadData(email);
string download = Encoding.ASCII.GetString(data);
HashSet<string> list = new HashSet<string>();
var doc = new HtmlDocument();
doc.LoadHtml(download);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@href]");
foreach (var n in nodes)
{
string href = n.Attributes["href"].Value;
list.Add(href);
}
return list.ToList();
}
Puoi controllare il valore HREF se è relativo URL o assoluto. Carica il link in un Uri e verifica se è relativo Se convertirlo in assoluto sarà la strada da percorrere.
static void Main(string[] args)
{
List<string> linksToVisit = ParseLinks("https://www.facebook.com");
}
public static List<string> ParseLinks(string urlToCrawl)
{
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadData(urlToCrawl);
string download = Encoding.ASCII.GetString(data);
HashSet<string> list = new HashSet<string>();
var doc = new HtmlDocument();
doc.LoadHtml(download);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@href]");
foreach (var n in nodes)
{
string href = n.Attributes["href"].Value;
list.Add(GetAbsoluteUrlString(urlToCrawl, href));
}
return list.ToList();
}
Funzione per convertire l'URL relativo in assoluto
static string GetAbsoluteUrlString(string baseUrl, string url)
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
uri = new Uri(new Uri(baseUrl), uri);
return uri.ToString();
}