Sample code for 30+ languages & platforms
Swift

HTML Table to CSV

See more HTML-to-XML/Text Examples

Demonstrates a method for converting an HTML table to a CSV file.

Note: This example requires Chilkat v9.5.0.77 or greater.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // First download the HTML containing the table
    let http = CkoHttp()!
    let bdHtml = CkoBinData()!

    success = http.quickGetBd(url: "https://example-code.com/data/etf_table.html", binData: bdHtml)
    if success != true {
        print("\(http.lastErrorText!)")
        return
    }

    // Convert to XML.
    let htx = CkoHtmlToXml()!
    htx.setHtmlBd(bd: bdHtml)

    let sbXml = CkoStringBuilder()!
    htx.toXmlSb(sb: sbXml)

    let xml = CkoXml()!
    xml.loadSb(sb: sbXml, autoTrim: true)

    // Remove attributes and sub-trees we don't need.
    // (In other words, we're getting rid of clutter...)
    var numRemoved: Int = xml.pruneTag(tag: "thead").intValue
    numRemoved = xml.pruneAttribute(attrName: "style").intValue
    numRemoved = xml.pruneAttribute(attrName: "class").intValue

    // Scrub the element and attribute content.
    xml.scrub(directives: "ContentTrimEnds,ContentTrimInside,AttrTrimEnds,AttrTrimInside")

    // Let's see what we have...
    print("\(xml.getXml()!)")

    // We have the following XML.
    // Copy this XML into the online tool at Generate Parsing Code from XML
    // as a starting point for accessing the data..

    // <?xml version="1.0" encoding="utf-8"?>
    // <root>
    //     <html>
    //         <head>
    //             <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    //         </head>
    //         <body text="#000000" bgcolor="#FFFFFF">
    //             <div>
    //                 <div>
    //                     <table role="grid" data-scrollx="true" data-sortdirection="desc" data-sorton="-1"/>
    //                 </div>
    //             </div>
    //             <div>
    //                 <table id="topHoldingsTable" role="grid" data-scrollx="true" data-sortdirection="desc" data-sorton="-1">
    //                     <tbody>
    //                         <tr role="row">
    //                             <td>
    //                                 <text>ITUB4</text>
    //                             </td>
    //                             <td>
    //                                 <text>ITAU UNIBANCO HOLDING PREF SA</text>
    //                             </td>
    //                             <td>
    //                                 <text>Financials</text>
    //                             </td>
    //                             <td>
    //                                 <text>Brazil</text>
    //                             </td>
    //                             <td>
    //                                 <text>10.94</text>
    //                             </td>
    //                             <td>
    //                                 <text>998,954,813.73</text>
    //                             </td>
    //                         </tr>
    //                         <tr role="row">
    //                             <td>
    //                                 <text>BBDC4</text>
    //                             </td>
    //                             <td>
    //                                 <text>BANCO BRADESCO PREF SA</text>
    //                             </td>
    //                             <td>
    //                                 <text>Financials</text>
    //                             </td>
    //                             <td>
    //                                 <text>Brazil</text>
    //                             </td>
    //                             <td>
    //                                 <text>9.01</text>
    //                             </td>
    //                             <td>
    //                                 <text>822,164,622.75</text>
    //                             </td>
    //                         </tr>
    // 			...
    // 			...
    // 			...
    //                     </tbody>
    //                 </table>
    //             </div>
    //         </body>
    //     </html>
    // </root>

    // 
    // This is the code generated by the online tool:
    // 
    var i: Int
    var count_i: Int
    var table_role: String?
    var table_data_scrollx: String?
    var table_data_sortdirection: String?
    var table_data_sorton: String?
    var table_id: String?
    var j: Int
    var count_j: Int
    var tr_role: String?
    var k: Int
    var count_k: Int
    var tagPath: String?
    var text: String?

    i = 0
    count_i = xml.numChildrenHavingTag(tag: "html|body|div").intValue
    while i < count_i {
        xml.i = i
        table_role = xml.chilkatPath(cmd: "html|body|div[i]|div|table|(role)")
        table_data_scrollx = xml.chilkatPath(cmd: "html|body|div[i]|div|table|(data-scrollx)")
        table_data_sortdirection = xml.chilkatPath(cmd: "html|body|div[i]|div|table|(data-sortdirection)")
        table_data_sorton = xml.chilkatPath(cmd: "html|body|div[i]|div|table|(data-sorton)")
        table_id = xml.chilkatPath(cmd: "html|body|div[i]|table|(id)")
        table_role = xml.chilkatPath(cmd: "html|body|div[i]|table|(role)")
        table_data_scrollx = xml.chilkatPath(cmd: "html|body|div[i]|table|(data-scrollx)")
        table_data_sortdirection = xml.chilkatPath(cmd: "html|body|div[i]|table|(data-sortdirection)")
        table_data_sorton = xml.chilkatPath(cmd: "html|body|div[i]|table|(data-sorton)")
        j = 0
        count_j = xml.numChildrenHavingTag(tag: "html|body|div[i]|table|tbody|tr").intValue
        while j < count_j {
            xml.j = j
            tr_role = xml.chilkatPath(cmd: "html|body|div[i]|table|tbody|tr[j]|(role)")
            k = 0
            count_k = xml.numChildrenHavingTag(tag: "html|body|div[i]|table|tbody|tr[j]|td").intValue
            while k < count_k {
                xml.k = k
                text = xml.getChildContent(tagPath: "html|body|div[i]|table|tbody|tr[j]|td[k]|text")
                k = k + 1
            }

            j = j + 1
        }

        i = i + 1
    }

    // Let's modify the above code to build the CSV.
    let csv = CkoCsv()!
    csv.setColumnName(index: 0, columnName: "Ticker")
    csv.setColumnName(index: 1, columnName: "Name")
    csv.setColumnName(index: 2, columnName: "Sector")
    csv.setColumnName(index: 3, columnName: "Country")
    csv.setColumnName(index: 4, columnName: "Weight")
    csv.setColumnName(index: 5, columnName: "Notional Vaue")

    i = 0
    count_i = xml.numChildrenHavingTag(tag: "html|body|div").intValue
    while i < count_i {
        xml.i = i
        j = 0
        count_j = xml.numChildrenHavingTag(tag: "html|body|div[i]|table|tbody|tr").intValue
        while j < count_j {
            xml.j = j
            k = 0
            count_k = xml.numChildrenHavingTag(tag: "html|body|div[i]|table|tbody|tr[j]|td").intValue
            while k < count_k {
                xml.k = k
                csv.setCell(row: j, col: k, content: xml.getChildContent(tagPath: "html|body|div[i]|table|tbody|tr[j]|td[k]|text"))
                k = k + 1
            }

            j = j + 1
        }

        i = i + 1
    }

    csv.saveFile(path: "qa_output/brasil_etf.csv")
    var csvStr: String? = csv.saveToString()
    print("\(csvStr!)")

    // Our CSV looks like this:
    // Ticker,Name,Sector,Country,Weight,Notional Vaue
    // ITUB4,ITAU UNIBANCO HOLDING PREF SA,Financials,Brazil,10.94,"998,954,813.73"
    // BBDC4,BANCO BRADESCO PREF SA,Financials,Brazil,9.01,"822,164,622.75"
    // VALE3,CIA VALE DO RIO DOCE SH,Materials,Brazil,8.60,"785,290,260.07"
    // PETR4,PETROLEO BRASILEIRO PREF SA,Energy,Brazil,5.68,"518,124,434.10"
    // PETR3,PETROBRAS,Energy,Brazil,4.86,"443,254,438.53"
    // B3SA3,B3 BRASIL BOLSA BALCAO SA,Financials,Brazil,4.57,"417,636,740.16"
    // ABEV3,AMBEV SA,Consumer Staples,Brazil,4.57,"417,216,913.63"
    // BBAS3,BANCO DO BRASIL SA,Financials,Brazil,3.25,"296,921,232.15"
    // ITSA4,ITAUSA INVESTIMENTOS ITAU PREF SA,Financials,Brazil,2.90,"265,153,684.52"
    // LREN3,LOJAS RENNER SA,Consumer Discretionary,Brazil,2.25,"205,832,175.98"
    // 

}