Searching browser contents after automated form submission - c#

Im using WatiN to automate form submissions on my website. The problem Im having is I cant find any documentation on how to search the page after submission and verify if a string is present or not. I need it to look for a string in the resulting page, and if it is present continue inserting the next variable in a list, if it is NOT present I need it to log what string was inserted that caused the text not to show up, preferably in a text file. Heres my code so far.
browser.GoTo("https://site.com");
// locate the form by name and fill it
browser.TextField(Find.ByName("form")).TypeText("example");
// click the submit button
browser.Button(Find.ByName("submit")).Click();
Unfortunately that's all I've gotten. Help is appreciated, I just need to be pushed in the right direction.

Use browser.ContainsText("text to find") to verify if a string is present or not.
string[] textToAddList = File.ReadAllLines(#"C:\Users\Syd\Desktop\list.txt");
browser.GoTo("https://site.com");
foreach (string textToAdd in textToAddList)
{
browser.TextField(Find.ByName("form")).TypeText(textToAdd);
browser.Button(Find.ByName("submit")).Click();
browser.WaitUntilComplete();
if (!browser.ContainsText("text to find"))
{
//Log here
break;
}
}

Related

Selenium webdriver + C#

I tried to ask question and i was asked to be specific so here I'll try to be specific as much as possible.
1)Check that not less than 4 news are displayed into the news section
-Check, that text “© 2019 Belarusian Railway” is displayed at the
bottom of the page
Check, that 5 buttons are present in the top part of the page: “Press
Center”, “Timetable”, “Passenger Services”, “Freight”, “Corporate”
here I tried to use location property with X and Y coordinates but
after I asked question to my mentor he said I won't be able to
determine it with this approach, so I have no idea how to check where
element is located
Type in “Поиск” input 20 random symbols (they should be different
for each execution). I know about sendKeys method but how do I make
my input random for each run
Check, that address in browser changed to the
https://www.rw.by/search/?s=Y&q=
Check, that text “К сожалению, на ваш поисковый запрос ничего не
найдено.” is displayed on a page
Clear entered random value from corresponding input, and enter
"Санкт-Петербург" instead
click the find button. I know how to do this step
Chech, that 15 links to the articles are displayed on the screen. No
idea how to do this
Write into the console text from that links
Here is the code for the tasks i managed to complete
[Test]
public void Test1()
{
var inputField = driver.FindElement(_inputField);
inputField.SendKeys("белорусская железная дорога");
var searchBtn = driver.FindElement(_searchButton);
Thread.Sleep(1000);
searchBtn.Click();
var targetUrl = driver.FindElement(_targetLink);
targetUrl.Click();
Assert.Pass();
}
}

Scraping with cefsharp

I have a problem I want to scraping with CefSharp, with what statement can I insert data into an input type = text in its property "value" and how can I get the contents of a table, all this using CefSharp
I have scraping with webbrowser native of .net but in the page that I want to realize the data collection when I load the page this hangs my program and closes it, the solution I found is to change the browser and use CefSharp since it does the task without problems, but now I do not know how to get the data, much less insert.
The code that I use with webbroser is the following
Insert information
foreach (HtmlElement etiqueta in webInterno.Document.GetElementsByTagName("input"))
{
//MessageBox.Show("input");
if (etiqueta.GetAttribute("name").Contains("strCurp"))
{
etiqueta.SetAttribute("value", txtCurp.Text);
}
}
Get information
webInterno.Document.GetElementsByTagName("input"))
{
//MessageBox.Show("input");
if (etiqueta.GetAttribute("name").Contains("strCurp"))
{
Info = etiqueta.InnerText;
}
}
this same thing that I do with the webbrowser control as I can do with cefSharp??
Thanks

c# fail to get element in content page with getelementbyid, getelementsbytagname

I have posted the same question but I post it again since I haven't got any answers to that post yet.
I am trying to get some information (such as tagName, id using GetElementsByTagName method or GetElementById method) from a content page in a website using winforms.
as you see the pictures attached, no matter which selection you make (select1, select2, select3 etc) web address stays same. however, contents under those selections are different in content page.
I am trying to access to a tagName(or id) from one of them(not selections but contents under a specific selection).
I have debugged and figured out(or seems like) I can not access to tagName(or id) from any of those contents under a specific selection.
It seems like I can only access tagName(or id) from main page. picture 3 will help better explanation of some terms such as main page, content page.
I tried to explain in detail, if my question seems still not clear, let me know plz.
My code looks like this.
var countGetFile = webBrowser1.Document.GetElementsByTagName("IFRAME");
foreach (HtmlElement l in countGetFile)
{
if (l.GetAttribute("width").Equals("100%"))
{
MessageBox.Show(l.GetAttribute("height").ToString());
MessageBox.Show(l.GetAttribute("outerText").ToString());
}
}
I was not able to grab information under 2 down level of #document from html.
html looks something like
...
<src="..." id="A" ... >
#document
...
<src="..." id="B" ... >
#document
...
<span="C" ...>
...
I could grab span information (third curly brackets) with codes looking like
HtmlWindow frame1 = webBrowser1.Document.GetElementById("A").Document.Window.Frames["A"];
HtmlWindow frame2 = frame1.Document.GetElementById("B").Document.Window.Frames["B"];
foreach (HtmlElement elm in frame2.Document.All)
{
if (elm.GetAttribute("tagName").Equals("C"))
{
// your command
}
}
to use Document.Window.Frames you need a header using "System.Collections";
btw, there is a problem. When I try to access to the information in third curly bracket, I need to do some kinds of work between frame1 and frame2 such as delaying for frame2 to have enough time to be able to access to next level after frame1.
I figured a kind of hack to get it through. Place a messagebox to pop up for short time delay, or place a delay function( not freeze ) with async code looking like,
async Task PutTaskDelay()
{
await Task.Delay(5000);//5 secs
}
I just found a temporary solution for accessing to second level. I will appreciate anyone who knows some ways to solve this problem.

Write into a log file with C#

I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}

How to track user response to confirm box, generated at runtime from c# code?

I am trying to get user confirmation from c# code behind file, to confirm if user wants to overwrite the existing file on server of cancel the operation but so far no luck.
this is my code :
if (File.Exists(filePath))
{
string alertMsg = #"confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Test", alertMsg, true);
}
else
{
fuPSD.SaveAs(filePath);
}
any help would be highly appreciated.
That code will pop up the message if the file exists and save it if it doesn't.
But you will need to take some action on the confirm dialog result on the client side and either trigger a postback or some other server call to perform the operation in the case of the override.
The problem is that your JavaScript registration will ask the user to confirm to overwrite the file after the next page loads. This then poses the issue of telling whether the user confirmed or denied from the server since you're confirm with be client side.
In the past I've used a hidden field to toggle true/false to show a popup from the server side. This gives me the ability to wire up the events to a delegate on the code behind(I.e make my own confirm box with my own buttons). You can still do this without it by I found that it leads to a lot of messy and hard to follow script like callin __doPostback manually.
something like this :
create
<asp:hiddenField id="hf" />* in the aspx file
also put on the JS location a Declaration :
var answer=null;
back to server :
string alertMsg = #"if (confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?')==true) answer='1'; else answer='0';";
now on the server side :
read :
hf.value

Categories