C#: How do you simulate html form submit

I'm locating images within web pages

Sometime when loading the page all you see is a link  once clicked the form is submitted and the image is shown
Is it possible to programmatically do this in C#?


Sample Form

<div id="continuetoimage" style="text-align:center;">
<form action="" method="POST">
<p>
<input id="continuebutton" type="submit" name="imgContinue" value="Continue to your image" />
</p>
</form>
</div>

Open in new window


This is as far as i've got

using System;
using System.Web;

using HtmlAgilityPack;
using System.Net;

					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
		string URL = "https://example.com/img-5b06f90905d08.html";
		ImgSRC = FindImg(URL);
	}
	private static string FindImg(string url){
		WebClient x = new WebClient();
        string source = x.DownloadString(url);
		int iForm = source.IndexOf("Continue to your image");
		string imageSRC ="";
		HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
		if(iForm >1){
		    
            document.LoadHtml(source);	
			foreach (HtmlNode input in document.DocumentNode.SelectNodes("//input[@type='submit']")){
				// Simulate clicking submit and download the responce
				source = x.DownloadString(SubmitResponce);
			}
		}
		 document.LoadHtml(source);
		
		foreach (HtmlNode link in document.DocumentNode.SelectNodes("//img"))
            {
          
                String tmp = link.GetAttributeValue("src", "");
                int jpgInt = tmp.IndexOf("jpg", StringComparison.OrdinalIgnoreCase);
                if (tmp != null && jpgInt >1)
                {
                    imageSRC = link.GetAttributeValue("src", "");
                    Console.WriteLine("ImgSRC = " + imageSRC);

                    
                }
                else
                {
                    continue;
                }
            }
            return imageSRC;

		
		
	}
}

Open in new window

LVL 1
trevor1940Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chinmay PatelChief Technical NinjaCommented:
Hi Tervor,

// This has to be a form level variable
WebBrowser browser= new WebBrowser();

// This code can go in your Init or form constructor itself.
            browser.SuspendLayout();
            browser.ScriptErrorsSuppressed = true;
            browser.Navigate("targeturl");
            browser.DocumentCompleted += Login_Browser_DocumentCompleted;


 private void Login_Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlElementCollection buttons = browser.Document.GetElementsByTagName("button");
            buttons[1].InvokeMember("Click");
        }

Open in new window


Instead of button, you would want to check the HTML, and find suitable elements. For example, SUBMIT or IMG.

Regards,
Chinmay.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Hi mate,

I'm not going to have time to look at this until the weekend so I'm closing it before the system starts complaining


What your suggesting looks promising

Thanx
0
Chinmay PatelChief Technical NinjaCommented:
Hi Tervor,

It is a working code - my ISP won't listen to my complains so I had to come up with an elaborate complaining system :P. This was the part of the entire shenanigans .

However, my suggestion is system does not complain for open questions - I think for 14 days or something, so no need to close them in advance.

Regards,
Chinmay.
0
trevor1940Author Commented:
I get messages regarding abandoned questions after 3 days

I had a brief play
// This has to be a form level variable
WebBrowser browser= new WebBrowser();


Is this a webbrowser on a windows form? and  loading the completed page, after the click,  into that?

I need to analysis the html after the click event
I'm unsure how to do that this could be due to bellow gets into an endless loop

        private void Login_Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlElement Inputs = browser.Document.GetElementById("continuebutton");
            //foreach(HtmlElement  HTMLInput in Inputs)
            //{
            //    string ID = HTMLInput.GetAttribute("id");
            //    if (ID == "continuebutton")
            //    {
            //        HTMLInput.InvokeMember("Click");
            //    }
            //}
            if (Inputs != null)
            {
               Inputs.InvokeMember("Click");
            }
        }
         

Open in new window

0
Chinmay PatelChief Technical NinjaCommented:
Is this a webbrowser on a windows form? and  loading the completed page, after the click,  into that?
Yes

I'm unsure how to do that this could be due to bellow gets into an endless loop

Oh Yes. Let me explain a bit on that part. You see we are attaching an event handler

browser.DocumentCompleted += Login_Browser_DocumentCompleted;

Open in new window

but then it will fire again when your initial page load completes. I simplified the code before posting - was not intentional to skip this part as it is crucial for entire thing to work. In my case I had to do multi page navigation to complete the task and I also ended up in the loop so what I did was this.

1. Navigate to page. For this I used browser.DocumentCompleted += Login_Browser_DocumentCompleted; (Attached Handler)
2. Then in Login_Browser_DocumentCompleted, I used browser.DocumentCompleted -= Login_Browser_DocumentCompleted;(Removed Handler), so that it will not fire again. I also added browser.DocumentCompleted += AfterLogin_Browser_DocumentCompleted;(Attached Another Handler) so a different event handler will handle the next page. In the Afterlogin handler i detach it and attach another one as needed..

Technically, you could use just one DocumentCompleted event but I think it might unnecessarily complicate things up ( you will have to maintain Switch or IF/Else).

I hope this will clarify things.

Regards,
Chinmay.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.