HTML Type Provider

This article demonstrates how to use the HTML type provider to read HTML tables files in a statically typed way.

The HTML Type Provider takes a sample HTML document as input and generates a type based on the data present in the columns of that sample. The column names are obtained from the first (header) row.

Introducing the provider

The type provider is located in the FSharp.Data.dll assembly. Assuming the assembly is located in the ../../../bin directory, we can load it in F# Interactive as follows:

open FSharp.Data

Parsing Power Market Data

The Elexon - BM Reports website provides market data about the U.K's current power system. For simplicity, an example of this data below is shown in CSV format.

Settlement Day,Period,IMBALNGC,Offer Volume Bid Volume,Accepted Offer Vol,Accepted Bid Vol,UAOV,UABV,PAOV,PABV

Usually with HTML files headers are demarked by using the tag, however in this file this is not the case, so the provider assumes that the first row is headers. (This behaviour is likely to get smarter in later releases). But it highlights a general problem about HTML's strictness.

type F1_2017 = HtmlProvider<"../data/2017_F1.htm", ResolutionFolder=__SOURCE_DIRECTORY__>

The generated type provides a type space of tables that it has managed to parse out of the given HTML Document. Each type's name is derived from either the id, title, name, summary or caption attributes/tags provided. If none of these entities exist then the table will simply be named Tablexx where xx is the position in the HTML document if all of the tables were flatterned out into a list. The Load method allows reading the data from a file or web resource. We could also have used a web URL instead of a local file in the sample parameter of the type provider. The following sample calls the Load method with an URL that points to a live version of the same page on wikipedia.

let url = 
  "https://en.wikipedia.org/wiki/" +

// Download the latest market depth information
let f1Calendar = 
  F1_2017.Load(url).Tables.``Season calendar``

// Look at the most recent row. Note the 'Date' property
// is of type 'DateTime' and 'Open' has a type 'decimal'
let firstRow = f1Calendar.Rows |> Seq.head
let round = firstRow.Round
let grandPrix = firstRow.``Grand Prix``
let date = firstRow.Date

// Print the bid / offer volumes for each row
for row in f1Calendar.Rows do
  printfn "Race, round %A is hosted at %A on %A" 
    row.Round row.``Grand Prix`` row.Date

The generated type has a property Rows that returns the data from the HTML file as a collection of rows. We iterate over the rows using a for loop. As you can see the (generated) type for rows has properties such as Grand Prix, Circuit, Round and Date that correspond to the columns in the selected HTML table file.

As you can see, the type provider also infers types of individual rows. The Date property is inferred to be a DateTime (because the values in the sample file can all be parsed as dates) while other columns are inferred as the correct type where possible.

Parsing Nuget package stats

This small sample shows how the HTML Type Provider can be used to scrape data from a website. In this example we analyze the download counts of the FSharp.Data package on NuGet. Note that we're using the live URL as the sample, so we can just use the default constructor as the runtime data will be the same as the compile time data.

// Configure the type provider
type NugetStats = 

// load the live package stats for FSharp.Data
let rawStats = NugetStats().Tables.``Version History``

// helper function to analyze version numbers from nuget
let getMinorVersion (v:string) =  

// group by minor version and calculate download count
let stats = 
  |> Seq.groupBy (fun r -> 
      getMinorVersion r.Version)
  |> Seq.map (fun (k, xs) -> 
      k, xs |> Seq.sumBy (fun x -> x.Downloads))
  |> Seq.toArray
type NugetStats = HtmlProvider<...>
val rawStats : HtmlProvider<...>.VersionHistory
val getMinorVersion : v:string -> string
val stats : (string * decimal) [] =
  [|("4.1", 2465M); ("4.0", 14039M); ("3.3", 489756M); ("3.2", 10290M);
    ("3.1", 146272M); ("3.0", 310599M); ("2.4", 355357M); ("2.3", 433617M);
    ("2.2", 272834M); ("2.1", 25314M); ("2.0", 73606M); ("1.1", 64927M);
    ("1.0", 15349M)|]

Getting statistics on Doctor Who

This sample shows some more screen scraping from Wikipedia:

let [<Literal>] DrWho = 

let doctorWho = new HtmlProvider<DrWho>()

// Get the average number of viewers for each doctor's series run
let viewersByDoctor = 
  doctorWho.Tables.``Season 1 (1963-1964) Edit``.Rows
  |> Seq.groupBy (fun season -> season.``Directed by``)
  |> Seq.map (fun (doctor, seasons) -> 
      let averaged = 
        |> Seq.averageBy (fun season -> 
            season.``UK viewers (millions)``)
      doctor, averaged)
  |> Seq.toArray
val DrWho : string =
  "https://en.wikipedia.org/wiki/List_of_Doctor_Who_episodes_(19"+[16 chars]
val doctorWho : HtmlProvider<...>
val viewersByDoctor : (string * float) [] =
  [|("Waris Hussein", 8.0); ("", nan); ("Christopher Barry", 8.275);
    ("Richard Martin", 10.025); ("Frank Cox", 7.9); ("John Crockett", 8.0);
    ("John Gorrie", 9.066666667); ("Mervyn Pinfield", 6.925);
    ("Henric Hirsch", 6.733333333)|]

Related articles

Multiple items
namespace FSharp

namespace Microsoft.FSharp
Multiple items
namespace FSharp.Data

namespace Microsoft.FSharp.Data
type F1_2017 = HtmlProvider<...>
type HtmlProvider =
<summary>Typed representation of an HTML file.</summary> <param name='Sample'>Location of an HTML sample file or a string containing a sample HTML document.</param> <param name='PreferOptionals'>When set to true, inference will prefer to use the option type instead of nullable types, <c>double.NaN</c> or <c>""</c> for missing values. Defaults to false.</param> <param name='IncludeLayoutTables'>Includes tables that are potentially layout tables (with cellpadding=0 and cellspacing=0 attributes)</param> <param name='MissingValues'>The set of strings recogized as missing values. Defaults to <c>NaN,NA,N/A,#N/A,:,-,TBA,TBD</c>.</param> <param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param> <param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 the for HTTP requests, unless <c>charset</c> is specified in the <c>Content-Type</c> response header.</param> <param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param> <param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource (e.g. 'MyCompany.MyAssembly, resource_name.html'). This is useful when exposing types generated by the type provider.</param>
val url : string
val f1Calendar : HtmlProvider<...>.SeasonCalendar
HtmlProvider<...>.Load(uri: string) : HtmlProvider<...>
Loads HTML from the specified uri
HtmlProvider<...>.Load(reader: System.IO.TextReader) : HtmlProvider<...>
Loads HTML from the specified reader
HtmlProvider<...>.Load(stream: System.IO.Stream) : HtmlProvider<...>
Loads HTML from the specified stream
val firstRow : HtmlProvider<...>.SeasonCalendar.Row
property Runtime.BaseTypes.HtmlTable.Rows: HtmlProvider<...>.SeasonCalendar.Row [] with get
module Seq

from Microsoft.FSharp.Collections
val head : source:seq<'T> -> 'T
val round : string
property HtmlProvider<...>.SeasonCalendar.Row.Round: string with get
val grandPrix : string
property HtmlProvider<...>.SeasonCalendar.Row.( Grand Prix ): string with get
val date : string
property HtmlProvider<...>.SeasonCalendar.Row.Date: string with get
val row : HtmlProvider<...>.SeasonCalendar.Row
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
type NugetStats = HtmlProvider<...>
val rawStats : HtmlProvider<...>.VersionHistory
val getMinorVersion : v:string -> string
val v : string
Multiple items
val string : value:'T -> string

type string = System.String
namespace System
namespace System.Text
namespace System.Text.RegularExpressions
Multiple items
type Regex =
  interface ISerializable
  new : unit -> unit + 4 overloads
  member GetGroupNames : unit -> string []
  member GetGroupNumbers : unit -> int []
  member GroupNameFromNumber : i: int -> string
  member GroupNumberFromName : name: string -> int
  member InitializeReferences : unit -> unit
  member IsMatch : input: string -> bool + 4 overloads
  member Match : input: string -> Match + 5 overloads
  member Matches : input: string -> MatchCollection + 4 overloads

System.Text.RegularExpressions.Regex(pattern: string) : System.Text.RegularExpressions.Regex
System.Text.RegularExpressions.Regex(pattern: string, options: System.Text.RegularExpressions.RegexOptions) : System.Text.RegularExpressions.Regex
System.Text.RegularExpressions.Regex(pattern: string, options: System.Text.RegularExpressions.RegexOptions, matchTimeout: System.TimeSpan) : System.Text.RegularExpressions.Regex
val stats : (string * decimal) []
property Runtime.BaseTypes.HtmlTable.Rows: HtmlProvider<...>.VersionHistory.Row [] with get
val groupBy : projection:('T -> 'Key) -> source:seq<'T> -> seq<'Key * seq<'T>> (requires equality)
val r : HtmlProvider<...>.VersionHistory.Row
property HtmlProvider<...>.VersionHistory.Row.Version: string with get
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>
val k : string
val xs : seq<HtmlProvider<...>.VersionHistory.Row>
val sumBy : projection:('T -> 'U) -> source:seq<'T> -> 'U (requires member ( + ) and member get_Zero)
val x : HtmlProvider<...>.VersionHistory.Row
property HtmlProvider<...>.VersionHistory.Row.Downloads: decimal with get
val toArray : source:seq<'T> -> 'T []
Multiple items
type LiteralAttribute =
  inherit Attribute
  new : unit -> LiteralAttribute

new : unit -> LiteralAttribute
val DrWho : string = "https://en.wikipedia.org/wiki/List_of_Doctor_Who_episodes_(1963%E2%80%931989)"
val doctorWho : HtmlProvider<...>
val viewersByDoctor : (string * float) []
property HtmlProvider<...>.Tables: HtmlProvider<...>.TablesContainer with get
property HtmlProvider<...>.TablesContainer.( Season 1 (1963-1964) Edit ): HtmlProvider<...>.Season119631964Edit with get
val season : HtmlProvider<...>.Season119631964Edit.Row
property HtmlProvider<...>.Season119631964Edit.Row.( Directed by ): string with get
val doctor : string
val seasons : seq<HtmlProvider<...>.Season119631964Edit.Row>
val averaged : float
val averageBy : projection:('T -> 'U) -> source:seq<'T> -> 'U (requires member ( + ) and member DivideByInt and member get_Zero)
property HtmlProvider<...>.Season119631964Edit.Row.( UK viewers (millions) ): float with get