在OCaml中读取URL的HTML内容

Sur*_*tor 7 html url ocaml

我想编写一个OCaml函数,它接受一个URL并返回一个由该位置的HTML文件内容组成的字符串.有任何想法吗?

非常感谢!

最好的,Surikator.

nlu*_*oni 9

我使用ocurl和nethtml完成了这两件事

ocurl来读取URL的内容(这里有大量的属性;这是最小的),

let string_of_uri uri = 
    try let connection = Curl.init () and write_buff = Buffer.create 1763 in
        Curl.set_writefunction connection
                (fun x -> Buffer.add_string write_buff x; String.length x);
        Curl.set_url connection uri;
        Curl.perform connection;
        Curl.global_cleanup ();
        Buffer.contents write_buff;
    with _ -> raise (IO_ERROR uri)
Run Code Online (Sandbox Code Playgroud)

nethtml ; (您可能需要设置DTD Nethtml.parse)

let parse_html_string uri = 
    let ch = new Netchannels.input_string (string_of_uri uri) in
    let docs = Nethtml.parse ?return_pis:(Some false) ch in
    ch # close_in ();
    docs
Run Code Online (Sandbox Code Playgroud)

干杯!

  • @nlucaroni,不需要调用global_cleanup(实际上当使用ocurl与其他代码一起使用时可能会有害),请使用`Curl.cleanup connection`.也应该检查HTTP返回码. (2认同)