2011-01-06 36 views
0

给定一个网址,我希望能够捕获该网址指向的页面的标题,以及 作为其他信息 - 例如第一个文本的片段段落在一个页面上? - 甚至可能是来自页面的图像。从页面获取数据,一个网址指向

Digg.com在提交网址时很好用。

这样的事怎么可能在.Net c#中完成?

回答

2

您正在寻找可以解析格式错误的HTML文档的HTML Agility Pack
您可以使用其HTMLWeb类来通过HTTP下载网页。


您还可以使用.Net的WebClient class通过HTTP下载文本。
但是,它不会帮助你解析HTML。

1

你可以尝试这样的事:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Net; 
using System.Text; 

namespace WebGet 
{ 
    class progMain 
    { 
     static void Main(string[] args) 
     { 
      ASCIIEncoding asc = new ASCIIEncoding(); 
      WebRequest wrq = WebRequest.Create("http://localhost"); 

      WebResponse wrp = wrq.GetResponse(); 
      byte [] responseBuf = new byte[wrp.ContentLength]; 

      int status = wrp.GetResponseStream().Read(responseBuf, 0, responseBuf.Length); 
      Console.WriteLine(asc.GetString(responseBuf)); 
     } 
    } 
} 

一旦你的缓冲区,你可以处理它寻找段落或图片的HTML标签中提取返回的数据的部分。

1

您可以使用如下函数提取页面的标题。您需要修改正则表达式来查找(比如说)第一段文本,但由于每个页面都不相同,因此这可能很困难。但是,您可以查找元描述标记并从中获取值。

public static string GetWebPageTitle(string url) 
{ 
    // Create a request to the url 
    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 

    // If the request wasn't an HTTP request (like a file), ignore it 
    if (request == null) return null; 

    // Use the user's credentials 
    request.UseDefaultCredentials = true; 

    // Obtain a response from the server, if there was an error, return nothing 
    HttpWebResponse response = null; 
    try { response = request.GetResponse() as HttpWebResponse; } 
    catch (WebException) { return null; } 

    // Regular expression for an HTML title 
    string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)"; 

    // If the correct HTML header exists for HTML text, continue 
    if (new List<string>(response.Headers.AllKeys).Contains("Content-Type")) 
     if (response.Headers["Content-Type"].StartsWith("text/html")) 
     { 
     // Download the page 
     WebClient web = new WebClient(); 
     web.UseDefaultCredentials = true; 
     string page = web.DownloadString(url); 

     // Extract the title 
     Regex ex = new Regex(regex, RegexOptions.IgnoreCase); 
     return ex.Match(page).Value.Trim(); 
     } 

    // Not a valid HTML page 
    return null; 
} 
0

您可以使用Selenium RC(开源,www.seleniumhq.org)来解析页面中的数据等。它是一个带有C#.Net库的Web测试自动化工具。

硒有完整的API来读取html页面上的特定项目。