2

如何简单地打开一个 url 并使用 D 从网页中读取数据?(如果需要使用标准的 lib 功能,我更喜欢 phobos 而不是 tango)

4

2 回答 2

4

curl 在标准库中。您可以像这样轻松获取 url:

import std.net.curl;
string content = get("d-lang.appspot.com/testUrl2");

http://dlang.org/phobos/std_net_curl.html#get

如果需要解析html,我写了一个dom库,很擅长。 https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff

抓住 dom.d 和 characterencodings.d 然后你可以:

import arsd.dom;
auto document = new Document();
document.parseGarbage(content); // content is from above, the html string

writeln(document.title); // the <title> contents
auto paragraph = document.querySelector("p");
if(paragraph is null)
     writeln("no paragraphs in this document");
else
     writeln("the first paragraph is: ", paragraph.innerText);

等等。如果您使用过 javascript dom api,这非常相似(尽管也以很多方式进行了扩展)。

于 2013-01-01T15:50:11.487 回答
3

我认为 std.net.curl 绑定是你最好的选择,特别是它的 get/post 方法(示例在文档中):http ://dlang.org/phobos/std_net_curl.html#get

毕竟,curl 是专门为这类任务设计的,绑定是 phobos 的一部分。

于 2013-01-01T15:47:50.960 回答