如何将HTML表格内容提取到DataTable

时间:2015-06-24 05:48:04

标签: c# html vb.net parsing href

我有this个html页面,页面中的内容如下所示

enter image description here

我正在尝试将页面中的内容提取到DataTable中并将其显示到网格中

例如在

<a href='/exodus-5.1/bacon/exodus-5.1-20150612-NIGHTLY-bacon.zip'>exodus-5.1-20150612-NIGHTLY-bacon.zip</a>

我需要获取链接的名称以及uri

名称: - exodus-5.1-20150612-NIGHTLY-bacon.zip
uri: - /exodus-5.1/bacon/exodus-5.1-20150612-NIGHTLY-bacon.zip

以下是我最终的结果

 Dim request As HttpWebRequest = HttpWebRequest.Create(url)
 request.Method = WebRequestMethods.Http.Get
 Dim response As HttpWebResponse = request.GetResponse()
 Dim reader As New StreamReader(response.GetResponseStream())
 Dim webpageContents As String = reader.ReadToEnd()
 response.Close()

1 个答案:

答案 0 :(得分:3)

虽然不是VB.Net,但使用另一种.Net语言F#和HTML Type Provider来实现这是一项非常简单的任务,FSharp.Data project是Nuget提供的{{3}}的一部分。

HTML类型提供程序为您提供对Visual Studio内HTML文档的类型访问,即

// Reference the FSharp.Data Nuget package
#r @".\packages\FSharp.Data.2.2.3\lib\net40\FSharp.Data.dll"
// Type provider over your HTML document specified in yourUrl
type html = FSharp.Data.HtmlProvider<yourUrl>
// Get the rows from the HTML table in the page
let allRows = html.GetSample().Tables.Table1.Rows |> Seq.skip 1
// Skip empty rows
let validRows = allRows |> Seq.where (fun row -> row.Name <> "")

然后将有效行加载到DataTable中:

// Reference the System.Data assembly
#r "System.Data.dll"
// Create a DataTable
let table = new System.Data.DataTable()
// Add column names to the table
for name in ["Parent";"Name";"Last modified";"Size"] do table.Columns.Add(name) |> ignore
// Add row values to the table
for row in validRows do
  table.Rows.Add(row.Column1, row.Name, row.``Last modified``, row.Size) |> ignore

最后在表单上显示DataTable:

// Reference the Windows.Forms assembly
#r "System.Windows.Forms.dll"
open System.Windows.Forms
// Create a form
let form = new Form(Width=480,Height=320)
// Initialise a grid
let grid = new DataGridView(Dock=DockStyle.Fill)
form.Controls.Add(grid)
// Set the grid data source with the table
form.Load.Add(fun _ -> grid.DataSource <- table)
form.Show()

以表格形式显示填充的DataGrid:

DataTable