【发布时间】:2018-06-04 23:05:37
【问题描述】:
我正在尝试使用 excel vba 从 aspx 页面检索表格数据。我知道如何从 URL 获取表格数据,但以下是主要问题。
问题
有一个 aspx 页面(比如 www.abc.aspx)。我目前在这个页面上。让这个页面成为page1。
现在我点击当前页面上的 page2 链接。值得注意的是,点击此链接后,旧网址(www.abc.aspx)没有变化,但内容发生了变化。(内容为page2)
如果您查看 page1 源代码
<form method="post" action="page1 url" id="Form1">
无论 page1 上的操作是什么(第 2 页点击),它都会发回相同的 page1 url。
那么,由于我不知道它的 URL,我如何在 excel VBA 中获取 page2 table 数据?
代码
这是我用来获取表格数据的。
我使用了 Internet Explorer 对象。然后导航到链接并将文档保存在 htmldoc 中。
ie.navigate "url"
Do While ie.READYSTATE <> READYSTATE_COMPLETE
Application.StatusBar = "Fetching data..."
DoEvents
Loop
Set htmldoc = ie.document
'Column headers
Set eleColth = htmldoc.getElementsByTagName("th")
j = 0 'start with the first value in the th collection
For Each eleCol In eleColth 'for each element in the td collection
ThisWorkbook.Sheets(1).Range("A1").Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time
j = j + 1 'move to next element in td collection
Next eleCol 'rinse and repeat
'Content
Set eleColtr = htmldoc.getElementsByTagName("tr")
'This section populates Excel
i = 0 'start with first value in tr collection
For Each eleRow In eleColtr 'for each element in the tr collection
Set eleColtd = htmldoc.getElementsByTagName("tr")(i).getElementsByTagName("td") 'get all the td elements in that specific tr
j = 0 'start with the first value in the td collection
For Each eleCol In eleColtd 'for each element in the td collection
ThisWorkbook.Sheets(1).Range("D3").Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time
j = j + 1 'move to next element in td collection
Next eleCol 'rinse and repeat
i = i + 1 'move to next element in td collection
Next eleRow 'rinse and repeat
ie.Quit
Set ie = Nothing
编辑:
示例
如果我们点击 Stack Overflow 中的问题 (https://stackoverflow.com/questions) 现在点击第2页的问题(新链接是https://stackoverflow.com/questions?page=2&sort=newest)
在我的例子中,如果我们点击page2,新链接不会更新。它是同一个旧链接。
编辑:我在这里发现了一个类似的问题
How do I get url that is hidden by javascript on external website?
谢谢。
【问题讨论】:
-
我在上面的问题中添加了检索表数据的代码。
-
@MaximilianPeters 我现在也举了一个例子。
-
如果页面是纯 html,那么来自 page2 的数据应该已经加载,只是隐藏。你应该能够得到它们。如果页面使用一些动态引擎,比如 Angular,那可能会更复杂,因为数据在附加的 javascript 文件中。您必须单击该 page2 按钮或在该 JS 文件中查找您的数据。
-
@EganWolf 是aspx