Daniel Hamutel
Daniel Hamutel

Reputation: 653

How can i click on a button on a website in c#?

In this code i'm using webbrowser to navigate to a site. Then i want to make a button click on the site.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web.UI;

namespace Click_On_Website_Button
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();

            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate("http://www.mysiteexample.com");


        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlElementCollection classButton = webBrowser1.Document.All;
            foreach (HtmlElement element in classButton)
            {
                if (element.GetAttribute("addMessage") == "button")
                {
                    element.InvokeMember("click");
                }
            }

        }
    }
}

When i'm doing View page source i search for addmessage and find:

http://www.mysiteexample.com

But when i'm running my program it's never get to the line:

element.InvokeMember("click");

When i make Inspect element on the website on the button to add a message it's on this:

<span class="addMessage" onclick="location='http://www.tapuz.co.il/forums/addmsg/393/טבע_ומזג_אוויר/מזג_האוויר'">  | הוספת הודעה</span>

In the source view the addmessage part is like this:

<div class="SecondLineMenu" id="SecondLineMenu">
                    <span class="addMessage"  onclick="location='http://www.tapuz.co.il/forums/addmsg/393/טבע_ומזג_אוויר/מזג_האוויר'" >  | הוספת הודעה</span>

Upvotes: 0

Views: 86

Answers (1)

MaxOvrdrv
MaxOvrdrv

Reputation: 1916

You should look for the ID or the Name...

GetAttribute ("addMessage") == "button"

Will never be true unless you have an element like this:

<input type="button" ... addMessage="button">

Upvotes: 1

Related Questions