I want to click a button on a web page automatically. I am using HtmlAgilityPack
. I can take the button's Xpath. But I could not fire the click event of the button. How can I do this? Please help.
4 Answers
Html Agility Pack is not supposed to be used to simulate clicks on buttons. It is used only for parsing HTML. If you want to send HTTP requests you could use a WebClient.
-
Can you pls give example of what method can I use to simulate automatic clicks?– juliaJul 3, 2011 at 17:55
-
If I understand Darin correctly, you can use the
WebClient
class to mimic a button click since a button click results in packaging data, and then performing a POST with the relevant data included as JSON or another format. Aug 10, 2013 at 12:53 -
But webClient method can fails if target website checking the host url or Verifying that request sent from same domain .. Sep 28, 2013 at 11:03
Have a look at the following answer: How to click a link element programmatially with HTMLElement?
He is creating a HtmlElement object (via xPath or by any other way) and then "invoking" the click event with the code:
htmlItem.InvokeMember("click");
I tried this using HAP but could not got a solution for clicking an input button. I used simplebrowser which worked like magic to achieve this.
An option that is a bit slow, but it works:
HtmlAgilityPack.HtmlNodeCollection ExpanderButtonNodes = Document.DocumentNode.SelectNodes("//div[@class='cd-expand-button']");
if (ExpanderButtonNodes != null)
foreach (HtmlAgilityPack.HtmlNode Node in ExpanderButtonNodes)
foreach (HtmlElement Element in webBrowser1.Document.GetElementsByTagName("div"))
if (Element.InnerText != null && Node.InnerText.Length > 0 && Element.InnerText.Contains(Node.InnerText))
Element.InvokeMember("click");
This could be improved upon but gives a base using two different ways to get to the same thing.