Selenium: Get the string out of a email textfield/textbox - c#

I want to get an email string out of an email textbox which was recently entered.
I'm doing automation tests with selenium and to confirm that the correct string was entered into the textbox, I want to recheck it before it goes on to the password textbox.
I saw a lot of examples here but the most are either getText(); (which seems to not work anymore) or getAttribute("Value");.
I debugged it, and the checkText gives always Null.
What im currently having is this code:
public static void SendKeysElement(IWebDriver webDriver)
{
IWebElement Field = webDriver.FindElement(By.XPath(selector));
Field.SendKeys("example#example.com");
string checkText = Field.GetAttribute("Value");
if (checkText != "example#example.com")
{
Console.WriteLine("String is wrong");
}
else
{
ConsoleWriteLine("String is correct");
}
}
Here is the inspect of that textbox, while the email string was entered.
The first thing I notice is, that the entered string in the email textbox is not displayed in the inspect.
The webpage is being written with .NET using a blazor template.

Instead of
.GetAttribute("Value")
try this :
.GetAttribute("value");
Note that, attribute type is case sensitive.

Related

Selenium WebDriver Validating Error Message Text

Please I am trying to validate error message text in a try catch and it is just catching every time. Need assistance with syntax or better way of the validation
string actualResultText = "";
string expectedResultText = "Error: Please Enter User Name";
IWebElement actualResult = webDriver.FindElement(By.XPath("//*[#id='id-7530880b3e6759b']/li/span[contains(text(),'Error: Please Enter User Name')]"));
actualResultText=actualResult.ToString();
if (actualResultText == expectedResultText)
{
result = true;
}
else
{
result = false;
}
Inspect
Please view this inspect against code
I'm working with selenium in python, but the answer might have something similar in C#.
In python, in order to get the text of an element you use:
element = driver.find_element(by, value) # get the element
print(element.text) # get the text of the element
The difference between here and what you are doing (again, if C# has something similar and it works the way I think it is) is using the attribute of the element object text, rather than converting the element object into a string.

Fix Element not Interactable Selenium C#

I am trying to create a raffle autocheckout on feature.com using C# and Selenium. I got through everything up to the payment page, where the payment fields (card,expiry, etc) are "not interactable". I've tried everything from using tag names, xpath, and nothing. This is my code:
const string cardName = "John A Doe";
const string expiry = "1224";
const string cvv = "001";
driver.FindElement(By.XPath("/html/body/div[3]/main/div[2]/div/div[3]/div[2]/div/div/div[2]/div/form/div[1]/div/input")).SendKeys(card);
driver.FindElement(By.Id("card-holder")).SendKeys(cardName);
driver.FindElement(By.Id("card-expiry-date")).SendKeys(expiry);
driver.FindElement(By.Id("card-cvc")).SendKeys(cvv);
My guess is that since this is a payment, it is probably in an iframe. You will need to switch to it and then add the cc info and the switch to main window to continue.
That first xpath needs to be fixed. That is a recipe for failure. If you post the html we can help you with a better path.
I just realized you posted the site. It is in an iframe and you can't get to the card name because it is in an iframe.
Based on this I would used the below but these fields are hidden which is always fun to deal with.
SwitchToIframeByXpath("//iframe[contains(#id, 'card-fields-number')]");
driver.FindElement(By.Xpath("//input[#placeholder='Card number']")).SendKeys(cardNum);
SwitchToMainContent;
SwitchToIframeByXpath("//iframe[contains(#id, 'card-fields-name')]");
driver.FindElement(By.Xpath("//input[#placeholder='Name on card']")).SendKeys(cardName)
SwitchToMainContent;
Rinse repeat for each field.
public static void SwitchToIframe(string frameName)
{
driver.SwitchTo().Frame(frameName);
}
or by xpath
public static void SwitchToIframeByXpath(string title)
{
driver.SwitchTo().Frame(driver.FindElement(By.XPath(title)));
}
Then switch to main
public static void SwitchToMainContent()
{
driver.SwitchTo().DefaultContent();
}

How do I assert the text in Google Search button with Selenium C#?

I tried to write the auto-test with Selenium using C# and asserts the text in Google Search Button.
However the test got failed.
How to do it correctly and what's wrong here?
enter code here
[Test]
public void TestIfButtonNameIsGoogleSearch()
{
Driver.Navigate().GoToUrl("https://www.google.com/?gws_rd=ssl");
var btnSearch = Driver.FindElements(By.Name("btnK"));
if(btnSearch.Count==2)
{
Assert.That(true);
}
string expName = btnSearch.LastOrDefault().Text;
Assert.AreEqual(expName, "Google Search");
}
Use .GetAttribute("value") instead of .Text
you can try the following code. By default inputs are holding the text in 'value' attribute. Normaly its hidden.
Code Example:
var btnSearch = Driver.FindElements(By.Name("btnK"));
var btnFeelingLucky = Driver.FindElements(By.Name("btnI"));
var searchBtnText = btnSearch.GetAttribute("value");
var feelingLuckyBtnText = btnFeelingLucky.GetAttribute("value");
Assert.AreEqual(searchBtnText , "Google Search");
Assert.AreEqual(feelingLuckyBtnText , "I'm Feeling Lucky");
If the 'value' does not return anything or its empty, you can try with:
string btnText = javaScriptExecutor.ExecuteScript("return arguments[0].value", searchBtnText) as string;

Get Search Queries from UrlReferer

I'm developing a website in ASP.Net 4. One of the requirements is to log search queries that people use to find our website. So, assuming that a URL parameter named "q" is present in Referrer, I've written the following code in my MasterPage's Page_Load:
if (!CookieHelper.HasCookie("mywebsite")) CookieHelper.CreateSearchCookie();
And my CookieHelper class is like this:
public class CookieHelper
{
public static void CreateSearchCookie()
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
if (HttpContext.Current.Request.UrlReferrer.Query != null)
{
string q = HttpUtility.ParseQueryString(HttpContext.Current.Request.UrlReferrer.Query).Get("q");
if (!string.IsNullOrEmpty(q))
{
HttpCookie adcookie = new HttpCookie("mywebsite");
adcookie.Value = q;
adcookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(adcookie);
}
}
}
}
public static bool HasCookie(string cookiename)
{
return (HttpContext.Current.Request.Cookies[cookiename] != null);
}
}
It seems ok at the first glance. I created a page to mimic a link from Google and worked like a charm. But it doesn't work on the host server. The reason is that when you search blah blah you see something like www.google.com/?q=blah+blah in your browser address bar. You expect clicking on your link in the results, will redirect to your site and you can grab the "q" parameter. But ,unfortunately, it is not true! Google, first redirects you to an address like:
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCgQFjAA&url=http%3A%2F%2Fwww.mywebsite.com%2F&ei=cks5Uof4G-aX0QXKhIGoCA&usg=AFQjCNEdmmYFpeRRRBiT_MGH5a1x9wUUlg&bvm=bv.52288139,d.d2k&cad=rja
and this will redirect to your website. As you can see the "q" parameter is empty this time! And my code gets an empty string and actually doesn't create the cookie (or whatever).
I need to know if there is a way to solve this problem and get the real "q" value. The real search term user typed to find my website. Does anybody know how to solve this?
Google stopped passing the search keyword:
http://www.searchenginepeople.com/blog/what-googles-keyword-data-grab-means-and-five-ways-around-it.html

Condition to compare strings in two fields but only if one field has evaluated to true

I have two Textboxes:
1. Textbox1 gets an email address (email textbox on a form)
2. Textbox two asks the user to confirm email
I need to compare the email address entered in Textboxes 1 by asking the user to re-enter in textbox 2. Then evaluate a statement and set a bool to true or false.
I read on all the Methods line String.Equals and others and tried using them.
I have these two variables in a class that I need to access in other parts on the program:
public static bool IsValidEmail { get; set; }
public static bool IsValidEmailConfirmed { get; set; }
if (!string.IsNullOrEmpty(checkEmail))
{
IsValidEmail = Regex.IsMatch(checkEmail, MatchEmailPattern);
}
else
{
IsValidEmail = false;
}
//VERIFY EMAIL ADDRESS MATCHES
//---------------------------
if (IsValidEmail == true)
{
IsValidEmailConfirmed = checkEmailConfirm.Equals(checkEmail);
}
else
{
IsValidEmailConfirmed = false;
}
The problem is I only want the confirm Textbox to request an entry if the initial Textbox pass validation. It would not make sense asking some to confirm a bad email address (format). So the user enters an email, if it fails, a confirmation is not requested, however this variable IsValidEmail = false; will evaluate to false which will indicate an error.
Finally if the first box pass validation and the confirmation fails, the error message ask for confirmation.
The code above is broken down as I have been trying to do different things.
Thanks for helping.
you don't specify if it's web forms or MVC, as MVC has a really powerful helpers for this, I'm going to assume that this is web forms.
from your code, you should refactor to:
IsValidEmail = !string.IsNullOrEmpty(checkEmail) && Regex.IsMatch(checkEmail, MatchEmailPattern);
//VERIFY EMAIL ADDRESS MATCHES
IsValidEmailConfirmed = IsValidEmail && checkEmailConfirm == checkEmail;
apart of that, I would also suggest to use jQuery Validate (assuming that you use jQuery already) and do this in the client as well.
<form ...>
Email: <input type="text" id="email" name="email" class="required email" />
Confirm email: <input type="text" id="email2" name="email2" class="required email" equalTo="#email" />
</form>
Live demo for jQuery Validate with equality among 2 fields: http://jsbin.com/imiten/1/
You could to nest the logic or change it from a property to a function.
Nest
if(validEmail)
{
if(!match)
{
'Code for non matching, flags/vars.
}
else
{
'Here is the point where all the data is validated.
}
}
else
{
'Code for invalid email, flags, variables
}
Or function
Public void validateEmail()
{
if(!validEmail)
{
'Set property
return; 'This will exit the function right here.
}
if(!matching)
{
'Set properties/vars
return; 'Another exit.
}
'If the code makes it here your data is valid
}

Categories

Resources