FSharp.Data


BinderScriptNotebook

HTML Parser

This article demonstrates how to use the HTML Parser to parse HTML files.

The HTML parser takes any fragment of HTML, uri or a stream and trys to parse it into a DOM. The parser is based on the HTML Living Standard Once a document/fragment has been parsed, a set of extension methods over the HTML DOM elements allow you to extract information from a web page independently of the actual HTML Type provider.

open FSharp.Data

The following example uses Google to search for FSharp.Data then parses the first set of search results from the page, extracting the URL and Title of the link. We use the HtmlDocument type.

To achieve this we must first parse the webpage into our DOM. We can do this using the HtmlDocument.Load method. This method will take a URL and make a synchronous web call to extract the data from the page. Note: an asynchronous variant HtmlDocument.AsyncLoad is also available

let results = HtmlDocument.Load("http://www.google.co.uk/search?q=FSharp.Data")

Now that we have a loaded HTML document we can begin to extract data from it. Firstly we want to extract all of the anchor tags a out of the document, then inspect the links to see if it has a href attribute, using HtmlDocumentExtensions.Descendants. If it does, extract the value, which in this case is the url that the search result is pointing to, and additionally the InnerText of the anchor tag to provide the name of the web page for the search result we are looking at.

let links =
    results.Descendants ["a"]
    |> Seq.choose (fun x ->
           x.TryGetAttribute("href")
           |> Option.map (fun a -> x.InnerText(), a.Value())
    )
    |> Seq.toList

Now that we have extracted our search results you will notice that there are lots of other links to various Google services and cached/similar results. Ideally we would like to filter these results as we are probably not interested in them. At this point we simply have a sequence of Tuples, so F# makes this trivial using Seq.filter and Seq.map.

let searchResults =
    links
    |> List.filter (fun (name, url) ->
                    name <> "Cached" && name <> "Similar" && url.StartsWith("/url?"))
    |> List.map (fun (name, url) -> name, url.Substring(0, url.IndexOf("&sa=")).Replace("/url?q=", ""))

Putting this all together yields the following:

[("FSharp.Data: Data Access Made Simplefsprojects.github.io › FSharp",
  "https://fsprojects.github.io/FSharp.Data/");
 ("fsprojects/FSharp.Data: F# Data: Library for Data Access - GitHubgithub.com › fsprojects › FSharp",
  "https://github.com/fsprojects/FSharp.Data/");
 ("FSharp.Data 4.2.4 - NuGetwww.nuget.org › packages › FSharp",
  "https://www.nuget.org/packages/FSharp.Data");
 ("Guide - Data Access | The F# Software Foundationfsharp.org › guides › data-access",
  "https://fsharp.org/guides/data-access/");
 ("Type Providers - F# | Microsoft Docsdocs.microsoft.com › Docs › .NET › F# guide",
  "https://docs.microsoft.com/en-us/dotnet/fsharp/tutorials/type-providers/");
 ("Working with data frames in F# - FsLabfslab.org › Deedle › frame",
  "https://fslab.org/Deedle/frame.html");
 ("What version of FSharp.Data is compatible with MSVS 2013?stackoverflow.com › questions › what-version-of-fsharp-data-is-compatible...",
  "https://stackoverflow.com/questions/66173158/what-version-of-fsharp-data-is-compatible-with-msvs-2013");
 ("Extracting data from websites with F# - Mark's Blogmallibone.com › post › ral-colour-table-with-fsharp",
  "https://mallibone.com/post/ral-colour-table-with-fsharp");
 ("F# Data: New type provider library - Tomas Petricektomasp.net › blog › fsharp-data",
  "http://tomasp.net/blog/fsharp-data.aspx/");
 ("F# Data Type Providers in .Net Core - Luke Merrettlukemerrett.com › fsharp-data-type-providers",
  "https://lukemerrett.com/fsharp-data-type-providers/");
 ("Learn more",
  "http://support.google.com/websearch%3Fp%3Dws_settings_location%26hl%3Den");
 ("Sign in",
  "https://accounts.google.com/ServiceLogin%3Fcontinue%3Dhttp://www.google.co.uk/search%253Fq%253DFSharp.Data%26hl%3Den")]
Multiple items
namespace FSharp

--------------------
namespace Microsoft.FSharp
Multiple items
namespace FSharp.Data

--------------------
namespace Microsoft.FSharp.Data
val results : HtmlDocument
Multiple items
module HtmlDocument from FSharp.Data
<summary> Module with operations on HTML documents </summary>

--------------------
type HtmlDocument = private | HtmlDocument of docType: string * elements: HtmlNode list override ToString : unit -> string static member AsyncLoad : uri:string * ?encoding:Encoding -> Async<HtmlDocument> static member Load : stream:Stream -> HtmlDocument + 2 overloads static member New : docType:string * children:seq<HtmlNode> -> HtmlDocument + 1 overload static member Parse : text:string -> HtmlDocument
<summary> Represents an HTML document </summary>
static member HtmlDocument.Load : reader:System.IO.TextReader -> HtmlDocument
static member HtmlDocument.Load : stream:System.IO.Stream -> HtmlDocument
static member HtmlDocument.Load : uri:string * ?encoding:System.Text.Encoding -> HtmlDocument
val links : (string * string) list
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * predicate:(HtmlNode -> bool) -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * names:seq<string> -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * name:string -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * predicate:(HtmlNode -> bool) * recurseOnMatch:bool -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * names:seq<string> * recurseOnMatch:bool -> seq<HtmlNode>
static member HtmlDocumentExtensions.Descendants : doc:HtmlDocument * name:string * recurseOnMatch:bool -> seq<HtmlNode>
module Seq from Microsoft.FSharp.Collections
<summary>Contains operations for working with values of type <see cref="T:Microsoft.FSharp.Collections.seq`1" />.</summary>
val choose : chooser:('T -> 'U option) -> source:seq<'T> -> seq<'U>
<summary>Applies the given function to each element of the list. Return the list comprised of the results "x" for each element where the function returns Some(x).</summary>
<remarks>The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently.</remarks>
<param name="chooser">A function to transform items of type T into options of type U.</param>
<param name="source">The input sequence of type T.</param>
<returns>The result sequence.</returns>
<exception cref="T:System.ArgumentNullException">Thrown when the input sequence is null.</exception>
val x : HtmlNode
static member HtmlNodeExtensions.TryGetAttribute : n:HtmlNode * name:string -> HtmlAttribute option
module Option from Microsoft.FSharp.Core
<summary>Contains operations for working with options.</summary>
<category>Options</category>
val map : mapping:('T -> 'U) -> option:'T option -> 'U option
<summary><c>map f inp</c> evaluates to <c>match inp with None -&gt; None | Some x -&gt; Some (f x)</c>.</summary>
<param name="mapping">A function to apply to the option value.</param>
<param name="option">The input option.</param>
<example><code> None |&gt; Option.map (fun x -&gt; x * 2) // evaluates to None Some 42 |&gt; Option.map (fun x -&gt; x * 2) // evaluates to Some 84 </code></example>
<returns>An option of the input value after applying the mapping function, or None if the input is None.</returns>
val a : HtmlAttribute
static member HtmlNodeExtensions.InnerText : n:HtmlNode -> string
static member HtmlAttributeExtensions.Value : attr:HtmlAttribute -> string
val toList : source:seq<'T> -> 'T list
<summary>Builds a list from the given collection.</summary>
<param name="source">The input sequence.</param>
<returns>The result list.</returns>
<exception cref="T:System.ArgumentNullException">Thrown when the input sequence is null.</exception>
val searchResults : (string * string) list
Multiple items
module List from Microsoft.FSharp.Collections
<summary>Contains operations for working with values of type <see cref="T:Microsoft.FSharp.Collections.list`1" />.</summary>
<namespacedoc><summary>Operations for collections such as lists, arrays, sets, maps and sequences. See also <a href="https://docs.microsoft.com/dotnet/fsharp/language-reference/fsharp-collection-types">F# Collection Types</a> in the F# Language Guide. </summary></namespacedoc>


--------------------
type List<'T> = | ( [] ) | ( :: ) of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex : rank:int * offset:int -> int member GetSlice : startIndex:int option * endIndex:int option -> 'T list static member Cons : head:'T * tail:'T list -> 'T list member Head : 'T member IsEmpty : bool member Item : index:int -> 'T with get ...
<summary>The type of immutable singly-linked lists.</summary>
<remarks>Use the constructors <c>[]</c> and <c>::</c> (infix) to create values of this type, or the notation <c>[1;2;3]</c>. Use the values in the <c>List</c> module to manipulate values of this type, or pattern match against the values directly. </remarks>
<exclude />
val filter : predicate:('T -> bool) -> list:'T list -> 'T list
<summary>Returns a new collection containing only the elements of the collection for which the given predicate returns "true"</summary>
<param name="predicate">The function to test the input elements.</param>
<param name="list">The input list.</param>
<returns>A list containing only the elements that satisfy the predicate.</returns>
val name : string
val url : string
System.String.StartsWith(value: string) : bool
System.String.StartsWith(value: char) : bool
System.String.StartsWith(value: string, comparisonType: System.StringComparison) : bool
System.String.StartsWith(value: string, ignoreCase: bool, culture: System.Globalization.CultureInfo) : bool
val map : mapping:('T -> 'U) -> list:'T list -> 'U list
<summary>Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection.</summary>
<param name="mapping">The function to transform elements from the input list.</param>
<param name="list">The input list.</param>
<returns>The list of transformed elements.</returns>
System.String.Substring(startIndex: int) : string
System.String.Substring(startIndex: int, length: int) : string
System.String.IndexOf(value: string) : int
System.String.IndexOf(value: char) : int
System.String.IndexOf(value: string, comparisonType: System.StringComparison) : int
System.String.IndexOf(value: string, startIndex: int) : int
System.String.IndexOf(value: char, comparisonType: System.StringComparison) : int
System.String.IndexOf(value: char, startIndex: int) : int
System.String.IndexOf(value: string, startIndex: int, comparisonType: System.StringComparison) : int
System.String.IndexOf(value: string, startIndex: int, count: int) : int
System.String.IndexOf(value: char, startIndex: int, count: int) : int
System.String.IndexOf(value: string, startIndex: int, count: int, comparisonType: System.StringComparison) : int