问题
I am trying to pull mortgage rates from a bank website into Excel 2010. This is the applicable website: http://www.bmo.com/home/personal/banking/rates/mortgages
I have created a web query in Excel to do this: (Data --> From Web --> "web site"). Looking through a browser, the page displays actual rates. In Excel, I only get placeholders like this:
Mortgage Rates
5 year Low Rate (closed) %*
Prime Rate %
The problem seems to be that Excel does not recognize the dynamic content on the webpage. If I "view source" for the data of interest, I see that the rates are populated by javascript variables:
<td class="ratesSubLabel">Prime Rate</td>
<td class="rate"><script type="text/javascript">document.write(prime.value);</script>%</td>
Can anyone help with this?
回答1:
I've never really used the web source type thing before (it never worked how I wanted).
You can use VBA to scrape the data from the page into Excel.
The following should read the data from the table on the site and print the results into sheet1.
' The following code should be put in a new code module
' Requires "Microsoft Internet Controls" and "Microsoft HTML Object Library" References
Sub Main()
Dim Browser As InternetExplorer
Dim Document As HTMLDocument
Dim Element As IHTMLElement
Dim Elements As IHTMLElementCollection
Dim Child As IHTMLElement
Dim Children As IHTMLElementCollection
Dim Row As Integer
Dim Column As Integer
Row = 1
Set Browser = New InternetExplorer
Browser.Navigate "www.bmo.com/home/personal/banking/rates/mortgages"
Do While Browser.Busy And Not Browser.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementsByTagName("table")(0).getElementsByTagName("tr")
Debug.Print Elements.Length
For Each Element In Elements
Column = 1
'Dim Children As IHTMLElementCollection
'Dim Child As IHTMLElement
Set Children = Element.getElementsByTagName("td")
For Each Child In Children
ThisWorkbook.Worksheets("Sheet1").Cells(Row, Column).Value = Child.innerText
Column = Column + 1
Next Child
Row = Row + 1
Next Element
End Sub
来源:https://stackoverflow.com/questions/20620604/excel-web-query-for-dynamic-data