views:

45

answers:

1

Hello, I am working on a vb.net program, I want to click a hyperlink on a page, the source look like this:

<a href="user_messages_view.php?id=23112">messages for Today, 2010-10-19 </a>

I want to check it everyday too!

I tried to click it with the following methods(Both couldn't click the link!):

Dim theElementCollection As HtmlElementCollection
    Dim ctrlIdentity As String
     theElementCollection = WebBrowser1.Document.GetElementsByTagName("a")
     For Each curElement As HtmlElement In theElementCollection
    ctrlIdentity = curElement.GetAttribute("innerText").ToString
     If ctrlIdentity = Today.Date.ToString(Today.Date.ToString("dd")) Then
    curElement.InvokeMember("click")
     End If
     Next

and I tried this code too:

        If Me.WebBrowser1.Document.Links(i).InnerHtml.Contains(Today.Date.ToString("dd")) Then
    Me.WebBrowser1.Document.Links(i).InvokeMember("Click")
     End If
     Next

Any help would be appreciated! Thanks!

A: 

I've found that the best way to click links in a WebBrowser is using javascript. Try something like this:

WebBrowser1.Navigate("javascript:function%20x(){document.getElementById('foo').click()}x()")

You'll need to rewrite your above code in javascript but that's a piece of cake. You can test your javascript by copy-pasting it directly into the browser's location bar. This is also a reliable way to fill out forms.

Caveats:

  • Notice how the work that I want to do is wrapped in a function. This is needed if you want the javascript to do multiple statements. Wrap in a function and then invoke the function.
  • You can't navigate to a URL more than around 500 characters. (The limit isn't exactly 512 but it's close.) There's no warning, either, so keep it in mind.
  • Make sure you wait until the page is loaded. The ReadyState = Complete and IsBusy = False.
  • Clicking like this doesn't always generate the usual events that you get when you click a link.
  • "%20" is hex for space. I don't recall if this was strictly necessary in my code. Try it both ways.
Eyal
I like the javascript idea, but I want to look for the date string, so it won't click the wrong link. What if I want to click let's say the first 4 link that contains "id:333", can I do that!
Beho86
Write a loop in javascript, something like for(var e in document.getElementsByTagName("a")) {if(e.getAttribute("href").test("id:333")) e.click();} More or less. Basically you're converting your code from VB.Net to javascript.
Eyal