VB.Net Automated login to WordPress site

Here is a handy little method that will automate the login process of a WordPress blog/site using VB.Net. This has many uses, such as scraping data from WordPress blogs, adding new posts to a blog from an application, or any other uses you can think of.

Private Sub LogInToWordpress(ByVal username As String, ByVal password As String)
Dim wbd As HtmlDocument = WebBrowser1.Document
Dim usernameinput, passwordinput As HtmlElement
usernameinput = wbd.GetElementById(“user_login”)
passwordinput = wbd.GetElementById(“user_pass”)

‘Set the values to the passed arguments
usernameinput.SetAttribute(“value”, username)
passwordinput.SetAttribute(“value”, password)

‘Now Submit the form
Dim submitbutton As HtmlElement
submitbutton = wbd.GetElementById(“wp-submit”).InvokeMember(“click”)
End Sub

To use it in your code, simply call LogInToWordpress and supply it two parameters, the username and password with which you wish to log in with.

LogInToWordpress(“admin”, “p@ssw0rd!”)

That’s it!

Here’s how it works…

WordPress is “developer-friendly”, in that it uses ID’s and names throughout the HTML to identify different document objects. This saves us from having to loop through all the objects of the same type and performing conditional statements to see if we have the right one. With this in mind, we can use the “GetElementById” method of the HTMLDocument class to retrieve the object with the given ID. In WordPress’ case, the 3 objects we are after are titled, “user_login”, “user_pass” and the submit button “wp-submit”.

Here is the HTML of those 3 elements:

'<input type="text" name="log" id="user_login" class="input" value="" size="20" tabindex="10" />
'<input type="password" name="pwd" id="user_pass" class="input" value="" size="20" tabindex="20" />
'<input type="submit" name="wp-submit" id="wp-submit" class="button-primary" value="Log In" tabindex="100" />

What my method does, is fetches the first two elements, the input fields and uses the “SetAttribute” method of the HTMLDocument class to “fill in” the values of these fields programatically. We fill them in with the arguments we pass to the method, the username and password. After that, we use the “InvokeMember” method to programatically “click” the submit button once the fields are populated.

This should hopefully help you speed up the process of logging in to a WordPress blog from your VB.Net application, and should give you an idea of how the process works if you wanted to automate logging in to other sites that require authentication.

Comments welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *