本文實例講述了C#基于正則表達式抓取a標簽鏈接和innerhtml的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//讀取網頁html string text = File.ReadAllText(Environment.CurrentDirectory + "//test.txt" , Encoding.GetEncoding( "gb2312" )); string prttern = "<a(\\s+(href=\"(?<url>([^\"])*)\"|'([^'])*'|\\w+=\"(([^\"])*)\"|'([^'])*'))+>(?<text>(.*?))</a>" ; var maths = Regex.Matches(text, prttern); //抓取出來寫入的文件 using (FileStream w = new FileStream(Environment.CurrentDirectory + "//wirter.txt" , FileMode.Create)) { for ( int i = 0; i < maths.Count; i++) { byte [] bs = Encoding.UTF8.GetBytes( string .Format( "鏈接地址:{0}, innerhtml:{1}" , maths[i].Groups[ "url" ].Value, maths[i].Groups[ "text" ].Value) + "\r\n" ); w.Write(bs, 0, bs.Length); Console.WriteLine(); } } Console.ReadKey(); |
圖解正則
朋友需要截取img標簽的src 和data-url 跟上面差不多。。順便附上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
string text =File.ReadAllText(Environment.CurrentDirectory + "//test.txt" , Encoding.GetEncoding( "gb2312" )); string prttern = "<img(\\s*(src=\"(?<src>[^\"]*?)\"|data-url=\"(?<dataurl>[^\"]*?)\"|[-\\w]+=\"[^\"]*?\"))*\\s*/>" ; var maths = Regex.Matches(text, prttern); //抓取出來寫入的文件 using (FileStream w = new FileStream(Environment.CurrentDirectory + "//wirter.txt" , FileMode.Create)) { for ( int i = 0; i < maths.Count; i++) { byte [] bs = Encoding.UTF8.GetBytes( string .Format( "圖片src:{0}, 圖片data-url:{1}" , maths[i].Groups[ "src" ].Value, maths[i].Groups[ "dataurl" ].Value) + "\r\n" ); w.Write(bs, 0, bs.Length); Console.WriteLine(); } } |
希望本文所述對大家C#程序設計有所幫助。