web scraping - how to login into a website programatically using asp.net -
i have performed below process in vb.net login website project ! here have taken webbrowser control , named webbrowser1
private void button1_click(object sender, eventargs e) { navigate("http://www.websitename.com"); webbrowser1.document.getelementbyid("webpagetextboxnameforusername") .innertext = "myusername"; webbrowser1.document.getelementbyid("webpagetextboxnameforpassword") .innertext = "mypassword"; webbrowser1.document.getelementbyid("webpagebuttonnametologin") .invokemember("click"); } public void navigate(string url) { webbrowser1.navigate(url); while(webbrowser1.readystate != webbrowserreadystate.complete) { application.doevents(); } }
now want follow same procedure in asp.net can people please me out here ?
thanks
here working example:
this class extends default .net webclient ability store cookies:
public class cookieawarewebclient : webclient { public void login(string loginpageaddress, namevaluecollection logindata) { var parameters = new stringbuilder(); foreach (string key in logindata.keys) { parameters.appendformat("{0}={1}&", httputility.urlencode(key), httputility.urlencode(logindata[key])); } parameters.length -= 1; var request = (httpwebrequest)webrequest.create(loginpageaddress); request.method = "post"; request.contenttype = "application/x-www-form-urlencoded"; var buffer = encoding.ascii.getbytes(parameters.tostring()); request.contentlength = buffer.length; using (var requeststream = request.getrequeststream()) { requeststream.write(buffer, 0, buffer.length); } var container = request.cookiecontainer = new cookiecontainer(); using (var response = request.getresponse()) { cookiecontainer = container; } } public cookieawarewebclient(cookiecontainer container) { cookiecontainer = container; } public cookieawarewebclient() : this(new cookiecontainer()) { } public cookiecontainer cookiecontainer { get; private set; } protected override webrequest getwebrequest(uri address) { var request = (httpwebrequest)base.getwebrequest(address); request.cookiecontainer = cookiecontainer; return request; } }
you can use this:
protected cookieawarewebclient getauthenticatedclient() { var client = new cookieawarewebclient(); var logindata = new namevaluecollection { { "email", "test@email.com" }, { "password", "testpassword" } }; client.login("https://myurl.com/login", logindata); return client; }
and navigate internal page using:
using (var client = getauthenticatedclient()) { var html = client.downloadstring("https://myurl.com/internalpage"); //do stuff received html here }
i'm using logic in asp.net projects.
Comments
Post a Comment