Wednesday 16 December 2009

How to get Source code of the target web page

Sometimes during the automation development I faced lots of problem when the source code functionality is disable of any target web page.

Then I thought do we have any alternative to solve this problem?
I searched/goggled somewhere here and there. At last I got some snip of code.

I customize the code in such a way that it helped me in 2 ways.
1. When source code functionally is disable of the target web page/web site.
2. When something failed (no control found) during running of automation code then just get the source code and save it in text file. Latter it would help me to find out why my automation code failed or Check for the controls id/value/text etc on that web page.

Below is the code for that

public void GetSourceCode()
{
try
{
//Target website/web page
string strUrlOfWebPage = "http://jawedm.blogspot.com";
//Location to store source code in text file.
string strTextFileLocation = "c://SourceFile.txt";
System.Net.WebRequest request = System.Net.HttpWebRequest.Create(urlOfWebPage);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)
request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader readerSource = new System.IO.StreamReader
(responseStream);
string strSourceForTextFile = readerSource.ReadToEnd();
readerSource.Close();
System.IO.File.WriteAllText(strTextFileLocation, strSourceForTextFile);

}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

Thanks ,
Md. jawed

2 comments:

Daaron said...

If you're using WatiN, you can get the source by using the browser object's Html property.

Otherwise, what you have is far more difficult than it needs to be. Try something like:
var client = new WebClient();
client.DownloadFile(strUrlOfWebPage, strTextFileLocation);

Anonymous said...

Hi,

I am using watiN to automate a overnight file download mechanism. I am using FileDownloadHandler. it works all well when i trigger the exe manully. But when i schedule it as NT job then I get time out error '
Has not shown dialog after 50 seconds'. I know it has something to do with the file download process. Is this would be treated as bug to be fixed in next release or there is any workaround?

Any help is appreciated.
Amit