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

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();

Related

Trouble selecting a hidden menu item using SeleniumBasic for vba

I am having some trouble selecting a hidden menu item on a work webpage using SeleniumBasic for vba. I have tried to use WebDriver.Mouse.MouseTo to hover over each menu option so that I can select the object nested "beneath" it, but after the first hover the object cannot be found.
In the picture below I intend to navigate like this:
Pricing Admin
System Admin
Multi-PAG Upload
To do this, I have to hover over Pricing Admin and subsequently hover over System Admin so that menu appears to click on Multi-PAG Upload. I have successfully gotten the driver to hover over Pricing Admin which brings up first menu list with three items ending in System Admin. However, trying to FindElement() for System Admin so that I can hover on it has proven very difficult.
I tend get an object required error or an XPath selector invalid depending on the method that I attempt. I start having problems at Set systemAdmin =.
Any advice would be welcome!
Public Sub SeleniumTest()
Dim driver As New WebDriver
'open chrome to site
driver.start "chrome"
driver.Get "http://www.website.net"
'login
driver.FindElementByName("j_username").SendKeys ("user")
driver.FindElementByName("j_password").SendKeys ("pass")
driver.FindElementById("submit_button").Click
'hover over Pricing Admin
Dim pricingAdmin As WebElement
Set pricingAdmin = driver.FindElementById("prcngAdmMnuFrm:prcngAdmMnu")
driver.Mouse.MoveTo pricingAdmin
Dim systemAdmin As WebElement
'neither selection method below works properly
' Set systemAdmin = driver.FindElementByXPath("//*[contains(text(),'System Admin')]")
' Set systemAdmin = driver.FindElementByXPath("//div[#id='prcngAdmMnuFrm:prcngAdmMnu']/div/div/ul/li/ul/li[3]/ul/li[4]/a/span/span")
driver.Mouse.MoveTo systemAdmin
Dim multiPagUpload As WebElement
' Set multiPagUpload = driver.FindElement("??")
multiPagUpload.Click
'closes browser window
driver.Quit
End Sub
Here is the (abridged) HTML for the site. I trimmed out a bit of the lists for simplicity's sake but if it's actually necessary (for using javascript, etc) let me know and I can pop more in.
<div id="prcngAdmMnuFrm:prcngAdmMnu" style="">
<div class="ui-widget ui-widget-content wijmo-wijmenu ui-corner-all ui-helper-clearfix wijmo-wijmenu-horizontal" aria-activedescendant="ui-active-menuitem" role="menubar">
<div class="scrollcontainer checkablesupport">
<ul style="display: block;" class="wijmo-wijmenu-list ui-helper-reset" tabindex="0">
<li role="menuitem" class="ui-widget wijmo-wijmenu-item ui-state-default ui-corner-all wijmo-wijmenu-parent" aria-haspopup="true" style="">
<a href="#" class="wijmo-wijmenu-link ui-corner-all" id="">
<span class="wijmo-wijmenu-text">
<span class="wijmo-wijmenu-text">Pricing Admin</span>
</span>
<span class="ui-icon ui-icon-triangle-1-s"></span>
</a>
<ul class="wijmo-wijmenu-list ui-widget-content ui-corner-all ui-helper-clearfix wijmo-wijmenu-child" style="display: none; left: 0px; top: 38px; position: absolute; list-style-type: none;" aria-hidden="true">
<li role="menuitem" class="ui-widget wijmo-wijmenu-item ui-state-default ui-corner-all wijmo-wijmenu-parent" aria-haspopup="true" style="">
<a href="#" class="wijmo-wijmenu-link ui-corner-all ui-state-focus">
<span class="wijmo-wijmenu-text">
<span class="wijmo-wijmenu-text">System Admin</span>
</span>
<span class="ui-icon ui-icon-triangle-1-e"></span>
</a>
<ul class="wijmo-wijmenu-list ui-widget-content ui-corner-all ui-helper-clearfix wijmo-wijmenu-child" style="display: none; left: 215px; top: -1px; position: absolute; list-style-type: none;" aria-hidden="true">
<li role="menuitem" class="ui-widget wijmo-wijmenu-item ui-state-default ui-corner-all">
<a onclick="showProcessingMessage('Loading');;var self = this; setTimeout(function() { var f = function(opt){ice.ace.ab(ice.ace.extendAjaxArgs({"source":"prcngAdmMnuFrm:menu_pad_sa_multi","execute":'#all',"render":'#all',"event":"activate"}, opt));}; f({node:self});}, 10);" style="cursor:pointer;" class="wijmo-wijmenu-link ui-corner-all">
<span class="wijmo-wijmenu-text">
<span class="wijmo-wijmenu-text">Multi-PAG Upload</span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<script type="text/javascript">
var widget_prcngAdmMnuFrm_prcngAdmMnu = ice.ace.create("Menubar", ["prcngAdmMnuFrm:prcngAdmMnu", {
"autoSubmenuDisplay": true,
"direction": "auto",
"animation": {
"animated": "fade",
"duration": 400
}
}]);
</script>
</div>
If I've left anything out that you need to troubleshoot, please let me know!
The xpath which is used in the code is not correct. my suggesting to find the anchor element and move the mouse over.
# System Admin Menu
'Hover over Pricing Admin
Dim systemAdmin As WebElement
Set systemAdmin = driver.FindElementByXPath("//a[.//span[contains(.,'System Admin')]]")
driver.Mouse.MoveTo pricingAdmin
If the mouse hover does not work, we can still try to handle the menu by clicking on the anchor element and then sendkeys (keys.Arrow_Right)
#Multi-PAG Upload
Dim multiPagUpload As WebElement
Set multiPagUpload = driver.FindElementByXPath("//a[.//span[contains(.,'Multi-PAG Upload')]]")
multiPagUpload.Click

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();
}
}

Selenium - Not able to Click Dynamically Visible Menu

I have a Menu which have li
(list) elements which gets enabled after you mouse-hover a particular label.
driver.get("www.snapdeal.com"); Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("loggedOutAccount"))).build().perform();
//Wait for 5 Secs
driver.findElement(By.className("accountLink")).click();// Here it's throwing Element not visible exception
This code is doing the mouse-hover properly but not able to click the "SignIn Link" Link. Though on manually checking the element is Visible
DOM Structure -
<div id="loggedOutAccount" class="hd-rvmp-logout">
<a class="signIn" href="javascript:void(0);">
<i class="iconHeader accountUser"></i>
<label class="my-account-lang"> My Account</label>
<i class="mar_2_left right-downArrow breadcrumbArrow-down"></i>
</a>
<div class="sdNavDropWrapper accDetails" style="display: none; z-index: 999;">
<ul class="positionAbsolute pull-right">
<li class="customLoggedInState">
<div class="left triangle"></div>
<div class="right triangle"></div>
<div>
<a class="accountLink" href="javascript:void(0);">Click here to sign in ></a>
</div>
</li>
<li class="stop-event">
<li class="stop-event">
<li class="stop-event">
<li class="stop-event">
<li class="stop-event">
</ul>
</div>
</div>
Please use xpath for both element like below :
driver.get("www.snapdeal.com");
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.xpath("yourxpathhere"))).build().perform();
driver.findElement(By.xpath("yourxpathhere")).click();
I think class/Id repeating for other elements also for style purpose. so Xpath is better to find unique element.

How to use webdriver to randomly click on a button with precondication

I'm trying to write a test script with flight booking tickets scenario like this: Randomly click a button which description contains keyword "tax not included",then results shows; Randomly click a button which not contains keyword, then price shows.
For instance: Go to ebay.com and search "iPhone",in the search result page,randomly click a url which label contains keyword "Buy It Now"...
Anybody got a clean solution to that? Thanks in advance.
I have no clue to handle this case...
here is my code:
public void flightSchedule(){
if (be.isTextPresent(locator.getValue("tax_text"), 1000)){ //if keywords displays
ArrayList<WebElement> lists = (ArrayList<WebElement>) be.getBrowserCore().findElements(contains(text(),'tax not included'));
Random random = new Random();
int ra = random.nextInt(lists.size());
WebElement element = (WebElement) lists.get(ra);
}
the page source code is:
<div id="itemBarXI151" class="avt_column avt_column_trans">
<div class="b_avt_lst">
<div class="avt_trans">
<div class="avt_column_1st">
<div class="avt_column_sp">
<p>
<span class="highlight">new york city</span>
(tax not included)
</p>
</div>
<div class="avt_column_2nd">
</div>
<div class="c6">
<div class="c7"> </div>
<div class="c8">
<div class="a_booking">
<a id="openwrapperbtnXI147" class="btn_book" title="booking tickets" onfocus="this.blur();" hidefocus="on" href="##" data-evtdataid="XI147">
<span>
<b>booking</b>
</span>
</a>
</div>
</div>
my xpath is:"//div[#class='avt_column avt_column_trans'] [contains(text(),'booking')]",but it doesn't work.

Issue with Drag and Drop element in Selenium Web driver with Java

In left pane there are some widgets the below code gives some idea about how the widgets are organized....
<div id="sites-widgets-1375699547529" class="sites-widget-container tab-content-div frog-touch-scroll active">
<div class="ui-editor-box">
<div class="image draggable" data-content="file/widget/0141D9112001BD9824CA7FB813F3CF04088C02AC50F154FA/icon.png" data-uuid="0141D9112001BD9824CA7FB813F3CF04088C02AC50F154FA" style="background-image:url(file/widget/0141D9112001BD9824CA7FB813F3CF04088C02AC50F154FA/icon.png);"/>
<div class="ui-editor-box-label">Text Activity</div>
</div>
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
<div class="ui-editor-box">
</div>
I want to drag and drop a widget to the container provided in the same web page. the code for the container is given below
<div class="sites-layout-one-one">
<div style="clear:both;"/>
<div class="bucket ui-sortable edit" data-order="1" data-attr="bucket"/>
<div style="clear:both;"/>
</div>
I'm trying to drag and drop the widget in to the container, but i cant able to do this, the code that i wrote is below
WebElement dragElement = driver.findElement(By.xpath("//div[#class='sites-widget-container tab-content-div frog-touch-scroll active']/div[#class='ui-editor-box'][1]"));
WebElement dropElement = driver.findElement(By.xpath("//div[#class='sites-layout-one-one']"));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(dragElement)
.moveToElement(dropElement)
.release(dropElement)
.build();
dragAndDrop.perform();
Thread.sleep(10000);
Please help me to sort out this...
Thanks in Advance
Shiva..
Just use the built in dragAndDrop action to handle this for you:
Actions builder = new Actions(driver);
builder.dragAndDrop(dragElement, dropElement).perform();
The API documentation is located here, which shows the usage for the dragAndDrop action:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html