How Can I Use VBA To Access A WebPage (IHTMLDocument?)
Using the following code, I can open up an Internet Explorer window and navigate to the website. I would like to go further by being able to have a code click through one of the links (such as "Boxing/UFC").
Sub Run()
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.Navigat开发者_高级运维e2 "http://www.bet365.com"
Do Until .ReadyState = 4: DoEvents: Loop
.Quit
End With
Because that link leads to a Javascript onclick
event (onclick="gS(1020,9);return false;"
) can you suggest code I could use that would enable VBA to click through that link without the user's interference once the VBA macro is run?
In Internet Explorer, you can simply click a link via the DOM API.
Retrieve the DOM node (the A
) you are interested in, and call click()
on it. This will also fire all associated event handlers.
EDIT: In your case, with VBA, do something like this (untested, I don't have VBA here)
Dim sideNav As IHTMLElement
Dim navLinks As IHTMLElementCollection
Dim currLink As IHTMLElement
Set sideNav = IE.document.getElementByID("sln")
Set navLinks = sideNav.all.tags("A")
For Each currLink In navLinks
If Trim(currLink.innerText) = "Boxing/UFC" Then
currLink.Click
End If
Next currLink
You would need to query the html document, and retrieve the collection. Once you retrieve the collection you would need to iterate through the elements and click it.
I am pasting a snippet of the code here (click here for the entire code). This is in c++, but i am assuming it must be the same for VB too.
IHTMLElementCollection *spCollectEmbed;
spDocument->get_links(&spCollectEmbed);
if(spCollectEmbed)
{
// get all the links
long lLen;
spCollectEmbed->get_length(&lLen);
for (long i = 0; i < lLen; i++)
{
IDispatch *ppvdispOption;
IHTMLElement *interfaceHTMLElement;
VARIANT index;
index.vt = VT_I4;
index.lVal = i;
// get the item from the document
HRESULT hResult = spCollectEmbed->item(index, index, &ppvdispOption);
if(SUCCEEDED(hResult))
{
// query for the element
hResult = ppvdispOption->QueryInterface( IID_IHTMLElement,
(void **) &interfaceHTMLElement);
if(SUCCEEDED(hResult))
{
BSTR innerhtml;
interfaceHTMLElement->get_innerHTML(&innerhtml);
// click the links
interfaceHTMLElement->click();
Sleep(2000);
}
精彩评论