【问题标题】:Trying to extract Wikipedia JSON data using Excel VBA尝试使用 Excel VBA 提取维基百科 JSON 数据
【发布时间】:2019-07-18 03:13:53
【问题描述】:

我在 Excel 中有一列术语,我需要从中提取 Wikipedia 中的第一句话。 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”,但它没有返回任何结果,所以我显然做错了什么。任何帮助表示赞赏。

【问题讨论】:

  • 至少 Post 中描述的 URL 字符串和代码中导航的 URL 不同。代码 URL 仅获取 {"batchcomplete":""}。代码 URL 缺少标题部分,可能是拼写错误,请查看。

标签: json excel vba api web-scraping


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多