首页 > 解决方案 > 我想从网页中提取数据,但最后我无法在工作表中写入数据。数据是表格形式(多行,列)?

问题描述

无法从网页中提取数据以及在工作表中写入数据的问题。

子拉数据()

'宣言

Dim IE As Object
Dim doc As HTMLDocument

'开始申请

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

'导航

IE.navigate "https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTIDX&symbol=NIFTY&date=25APR2019"

'循环直到加载页面

Do While IE.Busy Or IE.readyState <> 4
Application.Wait DateAdd("s", 1, Now)
Loop

'将数据放入网页并点击提交

Set doc = IE.document

doc.getElementById("underlyStock").Value = ThisWorkbook.Sheets("URLList").Range("A2").Value
doc.parentWindow.execScript "goBtnClick('stock');", "javascript"

'循环直到加载页面

Do While IE.Busy Or IE.readyState <> 4
Application.Wait DateAdd("s", 1, Now)
Loop

'将数据从 elementid-“octable”拉到 sheet-“nse”

strVal = doc.getElementById("octable").innerText
ThisWorkbook.Sheets("nse").Range("A1").Offset(r, 0).Value = strVal
r = r + 1

结束子

我想要 nse 表中的表数据(表名称)。

标签: excelvba

解决方案


可以尝试这样的事情,我只尝试使用 Nifty Data Only 成功,因为我不知道除了 SBI 的“SBIN”之外的底层符号,即使在手动冲浪中它也会给出页面“内部服务器错误 - 读取”(可能是由于它是星期天)。

可以尝试使用您的标的符号(可能在适当的时间)

代码:

Sub pulldata()
'declaration
Dim IE As Object
Dim doc As HTMLDocument
'start application
Dim Tbl As HTMLTable, Cel As HTMLTableCell, Rw As HTMLTableRow, Col As HTMLTableCol
Dim TrgRw As Long, TrgCol As Long



Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
'navigation

IE.navigate "https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTIDX&symbol=NIFTY&date=25APR2019"
'loop until load page

Do While IE.Busy Or IE.readyState <> 4
Application.Wait DateAdd("s", 1, Now)
Loop
'put data in webpage and click on submit

Set doc = IE.document

'doc.getElementById("underlyStock").Value = ThisWorkbook.Sheets("URLList").Range("A2").Value
'doc.parentWindow.execScript "goBtnClick('stock');", "javascript"
'loop until load page

Do While IE.Busy Or IE.readyState <> 4
Application.Wait DateAdd("s", 1, Now)
Loop
'pull data from elementid- "octable" to sheet- "nse"

Set Tbl = doc.getElementById("octable")


TrgRw = 1
    For Each Rw In Tbl.Rows
    TrgCol = 1
        For Each Cel In Rw.Cells
        ThisWorkbook.Sheets("nse").Cells(TrgRw, TrgCol).Value = Cel.innerText
        TrgCol = TrgCol + Cel.colSpan   ' if Column span is > 1 multiple
        Next Cel
    TrgRw = TrgRw + 1
    Next Rw
End Sub

推荐阅读