Reputation: 67
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
HtmlDocument doc = logger.Document;
HtmlElement username = doc.GetElementById("loginUsername");
HtmlElement password = doc.GetElementById("loginPassword");
HtmlElement submit = doc.GetElementById("loginSubmit");
username.SetAttribute("value", "myusername");
password.SetAttribute("value", "mypassword");
submit.InvokeMember("click");
}
catch
{
}
}
Hello, I am trying to make a program that will log onto a website, and read some texts off to display it to the user. With the code above, I've made the webbrowser log in automatically so far.
On the page after logging in,
I want the program to click on the Timetable element. But it doesn't have its own id. How can I get access to it?
Is this even a right way to do it? How can I achieve what I want here? I couldn't do it myself so I put this question here!
Upvotes: 0
Views: 89
Reputation: 5
It's here. Just some foreach code.
bool login = false;
bool nav = false;
bool beware = true;
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
HtmlDocument doc = webBrowser1.Document;
if (login && !nav)
{
HtmlElement timetable = null;
foreach (HtmlElement link in doc.GetElementsByTagName("li"))
{
Console.WriteLine(link.InnerText);
if (beware)
{
timetable = link; //Avoiding NullExceptions
}
if (link.InnerText.Contains("Timetablelol"))
{
timetable = link; //Set the Timetable var.
beware = false; //Keep Timetable the kept element.
}
}
timetable.InvokeMember("click"); //Clicking on timetable link.
nav = true;
}
if (!login && !nav)
{
HtmlElement username = doc.GetElementById("loginUsername");
HtmlElement password = doc.GetElementById("loginPassword");
HtmlElement submit = doc.GetElementById("loginSubmit");
username.SetAttribute("value", "myusername");
password.SetAttribute("value", "mypassword");
submit.InvokeMember("click");
login = true;
}
}
catch
{
Console.WriteLine("Didn't work");
}
}
Upvotes: 0
Reputation: 4928
You don't need to click on the button, as you have the URL. You can call the URL directly and read the code that has been returned:
var req = (HttpWebRequest)WebRequest.Create(URL);
req.Method = "GET";
var resp = req.GetResponse();
using(var sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8))
{
string result = sr.ReadToEnd();
}
myResponse.Close();
You can see the data returned if you use a tool such as Fiddler.
Upvotes: 1
Reputation: 52185
From the MSDN page it would seem that your options are limited.
What you can try though, it to use Selenium instead. It will allow your application to interact with web components and also consume them through ID's, XPath and CSS Selectors, which would allow you for more flexibility than what you are currently using.
Selenium comes with its own C# wrapper. This tutorial should help you.
Upvotes: 1