尝试使用Excel VBA提取Wikipedia JSON数据

时间:2019-07-18 03:13:53

标签: json excel vba api web-scraping

我在Excel中有一列术语,我需要从中提取维基百科的第一句话。 Wiki为此提供了一个API,它可以为我提供所需的确切信息:“提取”下的https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=&exintro=&exsentences=1&&titles=Stack%20Overflow

我已经安装了VBA-JSON,我的代码在下面,但是我没有运气。我在这里Extract JSON in Excel VBA尝试了以下示例,但是关于“结果”对象,我收到了错误消息。

     Dim http As Object
     Dim term As String
     x = 2
     Set http = CreateObject("MSXML2.XMLHTTP")

     Do While Sheet2.Cells(x, 4) <> ""
     term = Sheet2.Cells(x, 4)

     Const sURL As String = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=&exintro=&exsentences=1&&titles="
     http.Open "GET", sURL & term, False
     http.send

     Dim jsonResponse As Dictionary
     Set jsonResponse = JsonConverter.ParseJson(http.responsetext)
     Debug.Print http.responsetext

    Sheet2.Cells(x, 5).Value = http.responsetext
    x = x + 1
    Loop

上面的代码实际上根本没有运行,所以我不知道该把重点放在哪里。我尝试使用“ Debug.Print http.responseText”,但是它没有返回任何结果,所以我显然做错了什么。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

Sheet2code name,不一定是可见名称,因此请首先验证正确的工作表。

添加option explicit并声明所有变量的类型

然后您的网址末尾有一个&。删除它,就可以了

Option Explicit
Public Sub test()
    Dim http As Object, term As String, x As Long
    x = 2
    Set http = CreateObject("MSXML2.XMLHTTP")

    Do While Sheet2.Cells(x, 4) <> ""
        term = Sheet2.Cells(x, 4)

        Const sURL As String = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=&exintro=&exsentences=1&titles="
        http.Open "GET", sURL & term, False
        http.send

        Dim jsonResponse As Dictionary
        Set jsonResponse = JsonConverter.ParseJson(http.responseText)
        Debug.Print http.responseText

        Sheet2.Cells(x, 5).Value = http.responseText
        x = x + 1
    Loop
End Sub