Home
IToolS
News
Feedback
Resources
Samples
Download
Documents
Sito
Web
Search
Login
My Blog
My Blog
Blog Part:
Title:
Pane:
Insert:
Add Module
Trovare tutti i link di una pagina html mediante Regular expressions
by
lupok
on
lunedì 19 novembre 2012 18:02
Per ottenere tutti i link presenti in una pagina html è sufficiente utilizzare un oggetto WebClient e un Regex opportunamente configurato, vediamo come:
Per prima cosa creiamo un'applicazione console in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HtmlLinkExtractor
{
class Program
{
static void Main(string[] args)
{
}
}
}
Importiamo qualche namespace per velocizzare la scrittura del codice:
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
Attraverso un oggetto WebClient scarichiamo il contenuto della pagina che ci interessa:
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
string source = client.DownloadString("http://www.albertoschiassi.it");
foreach (LinkItem link in LinkFinder.Find(source))
{
Console.WriteLine(link);
}
Console.ReadLine();
}
}
Qundi occorre definire un struttura in grado di contenere i link trovati dal nostro motore di ricerca:
public struct LinkItem
{
public string Href;
public string Text;
public override string ToString()
{
return Href + "\t" + Text;
}
}
Quindi passiamo all'implemntazione del motore di recerca che data una stringa contenente la pagina html estrae tutti i link attraverso un'espressione regolare:
static class LinkFinder
{
public static List
Find(string file)
{
List
list = new List
();
MatchCollection m1 = Regex.Matches(file, @"(
.*?)", RegexOptions.Singleline);
foreach (Match m in m1)
{
string value = m.Groups[1].Value;
LinkItem i = new LinkItem();
Match m2 = Regex.Match(value, @"href=\""(.*?)\""", RegexOptions.Singleline);
if (m2.Success)
{
i.Href = m2.Groups[1].Value;
}
string t = Regex.Replace(value, @"\s*<.*?>\s*", "", RegexOptions.Singleline);
i.Text = t;
list.Add(i);
}
return list;
}
}
File Under:
Blogs
My Blog
Print
Author
lupok
My Blog
Tags
OPCUA
(1)
ITOOLS
(1)
TEXTTOSPEECH
(1)
PropertyGrid
(1)
FilteredPropertyGrid
(1)
Filtered
(1)
Archive
<<
febbraio 2025
>>
l
m
m
g
v
s
d
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1
2
3
4
5
6
7
8
9
Quick links
Microsoft
Borsa italiana
Iprel
IToolS
DotNetNuke store
Ideone
Favorites
Copyright 2025 by AS.it
Termini di Utilizzo
Privacy