C# Click on HtmlElement With no ID only Class - c#

I am not using selenium nor anything else, i just want to do it on the webbrowser on the windows form application.
I have a windows form application and i want to click on a button with code but there is no ID.
I tried using a lot of different things found on this websites forums, but none of this works.

Have you tried using WebBrowser.GetElementByTagName("div") and then checking each element against attribute type=submit?
Your code should look something like
HtmlElement submit = FindSubmitElement(webBrowser1.Document);
submit?.InvokeMember("submit");
public HtmlElement FindSubmitElement(HtmlDocument document)
{
HtmlElementCollection elems = document.GetElementsByTagName("div"); // since your tag is div
// this will return collection, even in case there is just one div, find the first one, having an attribute 'type' with value 'submit'
foreach (HtmlElement elem in elems)
{
string type = elem.GetAttribute("type");
if (!string.IsNullOrEmpty(type) && type == "submit")
{
return elem; // if div tag with attribute type is found exit and return that html element
}
}
return null; // if no div tags found with an attribute 'type' return null
}
Check more on GetElementsByTagName method on the MSDN docs. Code is taken from there and adjusted to your need.

Related

dotnetbrowser c# help remove entire div

I am using TeamDev Dotnetbrowser, for a tests, so how can I remove entire div, without a id, just using classname, for example:
<div class="home modulo-testbar">test</p></div>
I hope someone could help me, please!
Regards.
Learning documentation, I found a way to "hide", but I still like remove entire div content.
I have created and used this code:
DOMDocument document = e.Browser.GetDocument();
List<DOMNode> divs = document.GetElementsByTagName("div");
foreach (DOMNode node in divs)
{
DOMElement element = node as DOMElement;
if (element.GetAttribute("class").ToLower().Contains("home modulo-testbar"))
{
element.SetAttribute("style","display:none");
}
}
From looking at DOMNode API docs, this seems like it should remove a node from its parent:
var parent = node.Parent;
if(parent != null) {
parent.removeChild(node);
}
Put the above code where you currently set the style attribute to hide the element.

Programmatically click button in C#

I'm trying to programmatically click a series of buttons on an HTML web page which looks as follows:
<div class="srp-actions blue-button"><a class="primary-action-button label" href="/people/invite?from=profile&key=243930744&firstName=Will&lastName=Yang&authToken=p8Oz&authType=OUT_OF_NETWORK&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_pri_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary" data-li-result-interaction="instant-connect" data-li-success-text="Invite Sent" data-li-connect-href="/people/contacts-search-invite-submit?memIds=243930744&authTokens=p8Oz&authTypes=OUT_OF_NETWORK&from=voltron&firstName=Will&lastName=Yang&isAjax=true&connectionParam=member_desktop_search_people-vertical-module&csrfToken=ajax%3A7824954558998584370&trk=vsrp_people_res_invite_act&trkInfo=VSRPsearchId%3A12487701484818103943%2CVSRPtargetId%3A243930744%2CVSRPcmpt%3Aprimary">Connect</a><div class="secondary-actions-trigger"><button role="button" class="trigger"><span>Secondary Actions</span></button><ul class="menu"><li>Send InMail</li><li>Share</li></ul></div></div>
Here's the current code to find the button element and perform the action:
HtmlElementCollection elements = webBrowser1.Document.GetElementsByTagName("a");
// First find and click "Connect" buttons
foreach (HtmlElement item in elements)
{
if (item.OuterHtml.Contains("action-button label") &&
!item.OuterHtml.Contains("Message") &&
item.OuterHtml.Contains("OUT_OF_NETWORK"))
{
item.SetAttribute("href", item.GetAttribute("data-li-connect-href"));
item.InvokeMember("Click");
}
}
The code properly find the anchor element, but the InvokeMember method doesn't seem to yield any result, any idea what is wrong?
The tag you are using does not specify exactly which specific tag you need:
x = webBrowser1.Document.GetElementsByTagName("a")
Instead try :
x= webBrowser1.Document.GetElementsById("anchor_id");
x.InvokeMember("click");
Or try using following method to verify whether its the intended tag you're using via attribute.
if (element.GetAttribute(attribute).Equals(attName))

Web browser control to fill <input> field

I'm trying to open a web page in my webbrowser control and change the value of input fields. Works good when I'm doing it like this webBrowser.Document.GetElementById("Email").SetAttribute("value", "example#example.com");
on a page with defined element Ids, but now I've encountered a page where the html/javascript looks something like this:
<input id="${Id}" name="${Id}" type="text" class="text field" value="${Value}" title="${ToolTip}" />
So my question is how do I find this specific input field from the C# code?
Try This
This is a C# coding
HtmlElement Elem = AutomationWebBrowser.Document.GetElementById('<your element ID>');
Elem.SetAttribute("value", '<value to assign in input control>');
Also you can use variables inside the GetElementById and SetAttribute function
You can find element by class name by using the following function,
public static HtmlElement GetHTMLElementByClass(HtmlDocument document, String className)
{
foreach (HtmlElement element in document.All)
{
if (element.GetAttribute("className") == className)
{
return element;
}
}
}

GetElementById without id and name HOW?

I need to click the button "Add" in the post new wordpress form, this button is to add tags to the post , the trouble is that button don't have the value and id propertie. Is just like that
the html for the button
input type="button" class="button tagadd" value="Add" tabindex="3"
my tries
webBrowser1.Document.GetElementById("button tagadd").InvokeMember("click");
webBrowser1.Document.GetElementById("Add").InvokeMember("click");
"GetElementById without id"
:-)
Unless you can change the markup for the button
What you need now is to traverse the entire DOM and look for a button in a known place. I'd suggest adding jquery if not already exist to be able for easier dom manipulation/search.
If you add jquery you could do something like $(".tagadd").click()
You could try doing
webBrowser1.document.getElementsByClassName("tagadd")
EDIT: Here is a script to create the getElementsByClassName function if it's not available http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
There is also this http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname.aspx but I've never used it.
Add an ID. Even if you're dynamically generating the buttons this should be trivial.
If you're using jQuery,
$('.tagadd')
will return a collection of everything with the tagadd class applied. You can further filter this by the other classes (button, etc)
Use this:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\s)" + className + "(?:$|\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass
&& elementClass.indexOf(className) != -1
&& hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
and another
Some browsers provide the method getElementsByClassName() which lets you select by class without using jQuery (which is a bit heavy if this is all you need). I haven't tested this so I'm not sure how widely it's supported.
Did I mention that you should give everything an ID?
use TagName isteed for example
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("class") == "button tagadd")
{
elem.InvokeMember("click");
}
}

C# Navigate to Anchors in WebBrowser control

We have a web browser in our Winforms app to nicely display history of a selected item rendered by xslt.
The xslt is writing out <a> tags in the outputted html to allow the webBrowser control to navigate to the selected history entry.
As we are not 'navigating' to the html in the strict web sense, rather setting the html by the DocumentText, I can't 'navigate' to desired anchors with a #AnchorName, as the webBrowser's Url is null (edit: actually on completion it is about:blank).
How can I dynamically navigate to Anchor tags in the html of the Web Browser control in this case?
EDIT:
Thanks sdolphion for the tip, this is the eventual code I used
void _history_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
_completed = true;
if (!string.IsNullOrEmpty(_requestedAnchor))
{
JumpToRequestedAnchor();
return;
}
}
private void JumpToRequestedAnchor()
{
HtmlElementCollection elements = _history.Document.GetElementsByTagName("A");
foreach (HtmlElement element in elements)
{
if (element.GetAttribute("Name") == _requestedAnchor)
{
element.ScrollIntoView(true);
return;
}
}
}
I am sure someone has a better way of doing this but here is what I used to accomplish this task.
HtmlElementCollection elements = this.webBrowser.Document.Body.All;
foreach(HtmlElement element in elements){
string nameAttribute = element.GetAttribute("Name");
if(!string.IsNullOrEmpty(nameAttribute) && nameAttribute == section){
element.ScrollIntoView(true);
break;
}
}
I know this question is old and has a great answer, but this hasn't been suggested yet, so it might be useful for others that come here looking for an answer.
Another way to do it is use the element id in the HTML.
<p id="section1">This is a test section</p>
Then you can use
HtmlElement sectionAnchor = webBrowserPreview.Document.GetElementById("section1");
if (sectionAnchor != null)
{
sectionAnchor.ScrollIntoView(true);
}
where webBrowserPreview is your WebBrowser control.
Alternatively, sectionAnchor.ScrollIntoView(false) will only bring the element on screen instead of aligning it with the top of the page

Categories

Resources