how to differentiate the answers format(Checkbox or Textarea etc.) while working with for loop - selenium

I have a scenario where 15 questions are there and i do have to select the answer either by selecting radiobutton or checkbox or Yes/No button or have to enter some text in textarea.
My following code successfully selecting the answer randomly whether its a radio/checkbox or Yes/No button and displays the selected option as an answer along with question on console.
But how do i check if its textarea and need to enter something with 'sendKeys? And how do i select more than one checkboxes? And how do i display the answer Yes or No onconsole?
public void AssessmentTest() throws Exception
{
List<WebElement>totalQSN = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div"));
List<WebElement> mainQuestions = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[2]/div"));
System.out.println("The Questions are::");
for(int i=0; i<totalQSN.size()-5; i++)
{
System.out.println("QUESTION:- " + mainQuestions.get(i).getText() + "["+ i +"]" );
Random rnd = new Random();
List<WebElement> subOptions = totalQSN.get(i).findElements(By.tagName("input"));
WebElement sValue = subOptions.get(rnd.nextInt(subOptions.size()));
sValue.click();
List<WebElement> subQsnList = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[3]/div/span/span"));
System.out.println(subOptions.size());
for(int j=0; j<subOptions.size(); j++)
{
if(subOptions.get(j).isSelected())
{
String selectedAnswer= subQsnList.get(j).getText();
System.out.println("ANSWER: - " + selectedAnswer);
System.out.println("\n");
}
}
} }
HTML Code is as under for each type of question.
<div id="individualQuestionAnswerContainer147" class="individual-question-answer-container" style="display: block;" xpath="1">
<div class="individual-questions-count-container"></div>
<div id="questionContainer147" style="clear: both; float: left;"></div> //Contains Question
<div id="questionAnswerContainer147" class="answers-container"></div> //Contains Answers
</div>
If the question having checkboxes, the code is
<div id="individualQuestionAnswerContainer148" class="individual-question-answer-container" style="" xpath="2"> Contains 4 checkbox(divs)
<div class="individual-questions-count-container"></div>
<div id="questionContainer148" style="clear: both; float: left;"></div>
<div id="questionAnswerContainer148" class="answers-container" style="">
<div class="answer-text">
<span class="answer-text-inner btn-assessment-answer">
<input type="checkbox" name="Checkbox148" id="Checkbox449" class="radio-assessment-answer">
<span style="display: table;">
Good
</span>
</span>
</div>
<div class="answer-text">
<span class="answer-text-inner btn-assessment-answer">
<input type="checkbox" name="Checkbox148" id="Checkbox450" class="radio-assessment-answer">
<span style="display: table;">
Mold
</span>
</span>
</div>
<div class="answer-text"></div>
<div class="answer-text"></div>
</div>
</div>
If question having 2 buttons(Yes/No), the code is
<div id="individualQuestionAnswerContainer155" class="individual-question-answer-container" style="" xpath="7"> Contains 2 options Yes or No
<div class="individual-questions-count-container"></div>
<div id="questionContainer155" style="clear: both; float: left;"></div>
<div id="questionAnswerContainer155" class="answers-container" style="">
<input type="button" value="Yes" id="Button477" class="btnClass_155 btn-assessment-answer" style="">
<input type="button" value="No" id="Button478" class="btnClass_155 buttonClicked btn-assessment-answer">
</div>
</div>
If question having textarea, the code is
<div id="questionAnswerContainer38" class="answers-container" xpath="1">
<textarea maxlength="50000" rows="2" cols="100" id="FreeTextarea38"></textarea>
</div>

Try using this structure..Hope this helps.
public void AssessmentTest() throws Exception
{
List<WebElement>totalQSN = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div"));//Assuming this xpath is correct
List<WebElement> mainQuestions = driver.findElements(By.xpath("//div[#id='assessmentQuestionAnswersContainer']/div/div[2]/div")); //Assuming this xpath is correct
System.out.println("The Questions are::");
for(int i=0; i<totalQSN.size()-5; i++)
{
System.out.println("QUESTION:- " + mainQuestions.get(i).getText() + "["+ i +"]" );
Random rnd = new Random();
String webeleTag=totalQSN.get(i).getTagName();
if(webeleTag.equals("input"))){
String webeleType=totalQSN.get(i).getAttribute("type");
switch(webeleType){
case:"checkbox":
//your code to select check box
case:"button":
//Only click event on answer
default:
}
}
else if(webeleTag.equals("textarea")){
//your code
}
else{
//Not text area,checkbox or radio something else
}
}
}

To detect if it is a text area, from the top of my head you can go
for .getTagName() this will return the tag of the element.
To get all the checkboxes you can use driver.findElements(By.id("questionAnswerContainer148")).toArray(new WebElement[0]) , this will return an array with the checkboxes and you can use some logic to click in the items you want from the list.
For the yes/no, I think that the driver.findElement(by).getAttribute("value") will return the content of the attribute.
Hope this helps you.

Related

My Blazor web app is giving me this error when I try to view a page

I do not know what the below error is trying to tell me...
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at GSG.WebApp.Client.Pages.Index.BuildRenderTree(RenderTreeBuilder __builder) in C:\Users\ZachKoman\internalhrtool\GSG.WebApp\Client\Pages\Index.razor:line 0
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
The error began when I tried testing these filter input boxes.
<!--Input fields for filtering-->
<div style="display:flex">
<div class="filter">
<BSLabel style="width=20%">Lastname: </BSLabel >
<BSInput InputType="InputType.Text" placeholder="name" #bind-Value="lastname" />
</div>
<div class="filter">
<BSLabel style="width=20%">Company: </BSLabel>
<BSInput InputType="InputType.Text" placeholder="Company" #bind-Value="company"/>
</div>
<div class="filter">
<BSLabel style="width=20%">Skill: </BSLabel>
<BSInput InputType="InputType.Text" placeholder="Skill" #bind-Value="skill[0]"/>
</div>
#for (int i = 1; i < skillFilterStatus; i++)
{
<div class="filter">
<BSLabel style="width=20%">Skill: </BSLabel>
<BSInput InputType="InputType.Text" placeholder="Skill" #bind-Value="skill[i]"/>
</div>
}
#if(skillFilterStatus != 0)
{
<div class="filterBttn">
<BSButton style="background-color: #ed1c24;" #onclick="FilterMinus"><i class="oi oi-minus" style="color: white" ></i></BSButton>
</div>
}
#if(skillFilterStatus < 2)
{
<div class="filterBttn">
<BSButton style="background-color: #8522e4;" #onclick="FilterClick"><i class="oi oi-plus" style="color: white" ></i></BSButton>
</div>
}
<div class="filterBttn">
<BSButton #onclick="ApplyFilter" style="background-color: #8522e4; color: white">Apply</BSButton>
</div>
</div>
#code
private int skillFilterStatus = 0;
private string lastname;
private string company;
private string[] skill;
private void ApplyFilter(){
Console.WriteLine(lastname+"-"+company+"-"+skill[0]+"-"+skill[1]+"-"+skill[2]);
}

how to click close or the confirm button or click background to dismiss the pop up

there is a pop up after adding item to cart but it does not pop sometimes
how can i have the loop, if there is pop up then click the close or continue button or just click the background to dismiss it.
if it does not pop then continue next step.
below is the element, it is pretty long. please help to check
<div class="a-popover-wrapper"><header class="a-popover-header"><h4 class="a-popover-header-content" id="a-popover-header-6">Add to Order</h4><button data-action="a-popover-close" class=" a-button-close a-declarative" aria-label="Close"><i class="a-icon a-icon-close"></i></button></header><div class="a-popover-inner" id="a-popover-content-6" style="height: auto; overflow-y: auto;">
<div id="abb-interstitial" class="a-section abb-interstitial">
<div id="abb-intl-product-view-B07KTYTTG9" class="a-section abb-intl-product-view" style="display: block;">
<!-- only true in interstitial popovers -->
<div class="a-row">
<div class="a-column a-span4 a-text-center abb-product-view-image-container">
<img src="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL160_.jpg" class="a-image-wrapper a-manually-loaded abb-product-image" id="" alt="" data-a-image-source="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL160_.jpg" data-a-hires="https://images-na.ssl-images-amazon.com/images/I/31STSohmOiL._SL500_.jpg">
</div>
<div class="a-column a-span8 a-span-last">
<h3 class="a-spacing-none">
<a class="a-link-normal abb-product-title" target="_blank" rel="noopener" href="/dp/B07KTYTTG9/ref=ods_dabb_B07KTYTTG9_productInfo">
AppleCare+ for 13-inch MacBook Pro (3 Years)
</a>
</h3>
<div class="a-section a-spacing-micro abb-product-merchant-container">
<span class="a-color-secondary">
from
<span class="abb-product-merchant">Amazon Digital Services LLC</span>
</span>
</div>
<div class="a-section a-spacing-micro abb-product-reviews">
<style type="text/css">
/*
* Fix for UDP-1061. Average customer reviews has a small extra line on hover
* https://omni-grok.amazon.com/xref/src/appgroup/websiteTemplates/retail/SoftlinesDetailPageAssets/udp-intl-lock/src/legacy.css?indexName=WebsiteTemplates#40
*/
.noUnderline a:hover {
text-decoration: none;
}
</style>
<div id="averageCustomerReviews" class="a-spacing-none" data-asin="B07KTYTTG9" data-ref="dpx_acr_pop_">
<span class="a-declarative" data-action="acrStarsLink-click-metrics" data-acrstarslink-click-metrics="{}">
<span id="acrPopover" class="reviewCountTextLinkedHistogram noUnderline" title="4.0 out of 5 stars">
<span class="a-declarative" data-action="a-popover" data-a-popover="{"max-width":"700","closeButton":"false","position":"triggerBottom","url":"/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?contextId=dpx&asin=B07KTYTTG9"}">
<a href="javascript:void(0)" class="a-popover-trigger a-declarative">
<i class="a-icon a-icon-star a-star-4"><span class="a-icon-alt">4.0 out of 5 stars</span></i>
<i class="a-icon a-icon-popover"></i></a>
</span>
<span class="a-letter-space"></span>
</span>
</span>
<span class="a-letter-space"></span>
<span class="a-declarative" data-action="acrLink-click-metrics" data-acrlink-click-metrics="{}">
<a id="acrCustomerReviewLink" class="a-link-normal" href="#customerReviews">
<span id="acrCustomerReviewText" class="a-size-base">2 customer reviews</span>
</a>
</span>
<script type="text/javascript">
P.when('A', 'ready').execute(function(A) {
A.declarative('acrLink-click-metrics', 'click', { "allowLinkDefault" : true }, function(event){
if(window.ue) {
ue.count("acrLinkClickCount", (ue.count("acrLinkClickCount") || 0) + 1);
}
});
});
</script>
<script type="text/javascript">
P.when('A', 'cf').execute(function(A) {
A.declarative('acrStarsLink-click-metrics', 'click', { "allowLinkDefault" : true }, function(event){
if(window.ue) {
ue.count("acrStarsLinkWithPopoverClickCount", (ue.count("acrStarsLinkWithPopoverClickCount") || 0) + 1);
}
});
});
</script>
</div>
</div>
<div class="a-section a-spacing-base abb-product-price">
<span class="a-size-medium a-color-secondary abb-product-list-price a-text-strike">
</span>
<span class="a-size-medium a-color-price abb-product-buying-price">
$269.00
</span>
</div>
<div class="a-section abb-product-feature-bullets">
<ul>
<li>AppleCare product must be purchased with an applicable Apple device. Terms & Conditions will be delivered via email post-enrollment and can be downloaded through your Digital Items Page (Your Account-->Games and Software).</li>
<li>AppleCare+ will automatically be enrolled at time of purchase, and Proof of Coverage will be emailed within 3 days after your device ships.</li>
<li>AppleCare+ for Mac extends your coverage to three years from your AppleCare+ purchase date and adds up to two incidents of accidental damage coverage</li>
<li>Each incident of accidental damage coverage is subject to a service fee of $99 for screen damage or external enclosure damage, or $299 for other damage, plus applicable tax</li>
<li>Get 24/7 priority access to Apple experts by chat or phone</li>
<li>Onsite repair for desktop computers: Request that a technician come to your work site</li>
<li>Mail-in repair for portable computers: Mail in your Mac using a prepaid shipping box provided by Apple</li>
<li>Carry-in repair: Take your Mac to an Apple Store or other Apple Authorized Service Provider</li>
<li>Hardware coverage for your Mac computer, battery, included accessories such as the power adapter, Apple memory (RAM), AirPort, and Apple USB SuperDrive</li>
<li>Software support for using macOS and iCloud, quick how-to questions about Apple-branded apps, such as Photos, iMovie, GarageBand, Pages, Numbers, Keynote, and more, connecting to printers and AirPort networks</li>
</ul>
</div>
</div>
</div>
<div class="a-row">
<div class="a-column a-span8 a-push4">
<div class="a-section a-spacing-mini a-spacing-top-base abb-intl-product-cta">
<div class="a-row a-spacing-top-base">
<div data-asin="B07KTYTTG9" class="a-checkbox abb-intl-product-ato"><label><input type="checkbox" name="" value="" autocomplete="off"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
<span class="a-text-bold">Add AppleCare+ for 13-inch MacBook Pro (3 Years) to your order</span>
</span></label></div>
</div>
</div>
</div>
</div>
</div>
<div id="abb-intl-pop-cta" class="a-section a-spacing-base">
<div class="a-row">
<div class="a-column a-span8 a-push4">
<span class="a-button a-button-primary abb-intl-ato abb-intl-continue" id="a-autoid-13"><span class="a-button-inner"><input class="a-button-input" type="submit" aria-labelledby="a-autoid-13-announce"><span class="a-button-text a-text-center" aria-hidden="true" id="a-autoid-13-announce">
Continue
</span></span></span>
<span class="a-button a-button-base abb-intl-decline aok-hidden" id="a-autoid-14"><span class="a-button-inner"><input class="a-button-input" type="submit" aria-labelledby="a-autoid-14-announce"><span class="a-button-text a-text-center" aria-hidden="true" id="a-autoid-14-announce">
No thanks
</span></span></span>
</div>
</div>
</div>
</div>
</div></div>
Try the following code.Hope this will work.
To click on continue try this
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='Continue']/parent::span/input[#class='a-button-input']"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='Continue']/parent::span/input[#class='a-button-input']"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
//To click on No Thanks try this
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='No thanks']/parent::span/input[#class='a-button-input']"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.Xpath("//span[normalize-space(.)='No thanks']/parent::span/input[#class='a-button-input']"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
//To close the popup
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.cssSelector("i.a-icon.a-icon-close"));
Actions action = new Actions(driver);
action.moveToElement(element).click().build().perform();
}
OR
if (driver.findElements(By.cssSelector("div.a-popover-wrapper")).size()>0){
WebElement element=driver.findElement(By.cssSelector("i.a-icon.a-icon-close"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();",element);
}
Here is the logic.
// change the action based on scenario
String action = 'Continue';
if (driver.findElements(By.Xpath("//div[#class='a-popover-wrapper']")).size()>0){
driver.findElement(By.Xpath("//div[#class='a-popover-wrapper']//span[#class='a-button-text a-text-center' and normalize-space(.)='" + action + "']")).click();
}
I am using python:
def escape_pop(driver):
try:
if len(str(driver.find_element_by_class_name("a-popover-wrapper"))) > 0: # check if popup is present
actions = ActionChains(driver)
actions.send_keys(Keys.ESCAPE).perform()
except:
pass
after trying many methods.
below is working.
i add a wait element
then add one more click.
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("a-autoid-13")));
driver.findElement(By.cssSelector("i.a-icon.a-icon-close")).click();

Count some images Using Selenium

I have the code below and want to count only the images in "galeria003" (I have others galleries with imgs on the page)
<div id="classepai" class="carrossel">
<div class="galeria003">
<div class="conjuntoimgs">
<div class="imagem_item">
<div>
<img src="https://localhost/foto1.jpg">
</div>
</div>
<div class="imagem_item">
<div>
<img src="https://localhost/foto2.jpg">
</div>
</div>
</div>
</div>
<div class="galeria004">
<div class="conjuntoimgs">
(...)
</div>
</div>
I tried with the code below, but it returns to me all the images on the page.
public int galeria03() {
List<WebElement> lista03 = driver.findElements(By.tagName("img"));
int count = 0;
for(WebElement e : lista03) {
count++;
}
return count;
You can use below xpath to get all image tag present in "galeria003"
List<WebElement> lista03 = driver.findElements(By.xpath("//div[#class='galeria003']//img"));
And print the total image element
System.out.println(lista03.size());

Autocomplete with Selenium

I'm having some (actually, a lot) of trouble automating selection from autocomplete options with Selenium. Currently, I am able to automate the inputting of the text, though, I am not able to select anything from the appearing drop-down suggestions list that pops up. I tried searching here for some answers to my problem, but nothing has worked. Below is the element that appears with the suggestions that I am trying to select:
<div class="cs-autocomplete-popup">
<div class="inner">
<div class="cs-autocomplete-Matches csc-autocomplete-Matches">
<ul>
<li class="cs-autocomplete-matchItem csc-autocomplete-matchItem">
<span class="csc-autocomplete-matchItem-content cs-autocomplete-matchItem-content" id="matchItem::matchItemContent">john doe</span>
</li>
</ul>
</div>
<div class="csc-autocomplete-addToPanel cs-autocomplete-addToPanel">
<hr>
<div class="content csc-autocomplete-addTermTo cs-autocomplete-addTermTo">Add "John Doe" to:</div>
<ul>
<li class="cs-autocomplete-authorityItem csc-autocomplete-authorityItem" id="authorityItem:">Local Persons</li>
</ul>
</div>
</div>
<div class="cs-autocomplete-popup-miniView csc-autocomplete-popup-miniView" style="top: 2px; left: 149px; display: none;"><div class="cs-miniView">
john doe
<div>
<span class="csc-autocomplete-popup-miniView-field1Label cs-autocomplete-popup-miniView-field1Label">b.</span>
<span class="csc-autocomplete-popup-miniView-field1 cs-autocomplete-popup-miniView-field1" id="field1"></span>
</div>
<div>
<span class="csc-autocomplete-popup-miniView-field2Label cs-autocomplete-popup-miniView-field2Label">d.</span>
<span class="csc-autocomplete-popup-miniView-field2 cs-autocomplete-popup-miniView-field2" id="field2"></span>
</div>
<div>
<span class="csc-autocomplete-popup-miniView-field3 cs-autocomplete-popup-miniView-field3" id="field3"></span>
</div>
<div>
</div>
</div></div>
</div>
From this, I am trying to select "john doe". Does anyone know an efficient/complete way of doing this? I would very much appreciate the help.
driver.findElement(By.xpath("get the exact field address of autocomplete textbox");
Thread.sleep(5000);
//for xpath: need to take the common xpath from the list of the elements.
List<WebElement> link=driver.findElements(By.xpath("//span[contains(#class, 'cs-autocomplete-matchItem-content') and .='john doe']");
for(int i=0; i<=link.size(); i++)
{
if(link.get(i).getText().equalsIgnoreCase("john doe");
{
link.get(i).click();
}
}

GEB find first visible element

I have got some hidden buttons on the page. When I click on text input, one of these buttons shows on the page. Before:
<div field='login'>
<input type="text">
<button class="submit" style="display: none">Save</button>
</div>
<div field='name'>
<input type="text">
<button class="submit" style="display: none">Save</button>
</div>
After click on second input:
<div field='login'>
<input type="text">
<button class="submit" style="display: none">Save</button>
</div>
<div field='name'>
<input type="text">
<button class="submit">Save</button>
</div>
So I try to interact with second button by next selectors in my test:
static content = {
submitButton { $("button.submit") }
}
but I have next error:
isorg.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
If I write:
static content = {
submitButton { $("button.submit", 1) }
}
it works, but I need to work with one first visible button on the page. What is wrong?
Unfortunately there is no css selector to find visible elements but you can use displayed property of Navigator and its findAll() method to find the button that is visible:
static content = {
submitButton { $("button.submit").findAll { it.displayed } }
}