How to select a <a href> javascript button using selenium java - java

I'm trying to click the "Add to Shopping Bag" button by utilising selenium (Java) interface on my AUT, but I'm unable to do so.
My script as follows:
public void addToBag()
{
WebElement AddToBag = null;
List<WebElement> SizeList = driver.findElement(By.className("selection-wrapper")).findElements(By.className("step-wrapper"));
for(WebElement e : SizeList)
{
if (e.getText() == " ")
{
if(e.findElement(By.tagName("span")).findElement(By.tagName("a")).getAttribute("href").contains("javascript:AddToCart()"))
{
AddToBag = e.findElement(By.tagName("span")).findElement(By.tagName("a"));
AddToBag.click();
break;
}
}
}
Thread.sleep(2000);
}
Source code:
<div class="subitem-steps span-12 last" style="z-index: 890;">`
<div class="item-styles span-12 last" style="z-index: 885;">`
<div class="selection-wrapper" style="z-index: 870;">`
<div class="step-wrapper" style="z-index: 869;">
<div class="step-wrapper" style="z-index: 863;">
<div class="step-wrapper" style="z-index: 857;">
<div class="step-wrapper" style="z-index: 851;">
<div class="step step4" style="z-index: 850;"/>
<span class="ui-btn-grey btn-add-to-cart btn-add-to-cart-sel">
<a href="javascript:AddToCart()" onclick="s_objectID="javascript:AddToCart()_1";return this.s_oc?this.s_oc(e):true"/>
</span>
<div class="external-links" style="z-index: 849;">
</div>
</div>
</div>`

Related

Spring annotation for a global scope of function variables?

I am working on a springboot+thymeleaf project. I have a page(form) which accepts user data (startdate and enddate),and a button(Check). On click of the button, backend does some validation. If there are errors, I print the errors on the textarea within the same page (below the check button). If there are no errors, then I activate another button below the textarea, to signify that the entries between the mentioned dates are ready to be stored in the database.
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div th:fragment="contentinput">
<div class="container-md">
<a>Import Worklogs</a>
<div class="row justify-content-md-end">
<form modelAttribute = "userData">
<div class="row">
<div class="col-2">
<input type="text" class="form-control" id="txtFrom"
placeholder="start date(yyyy-mm-dd)" name="dateFrom">
</div>
<div class="col-2">
<input type="text" class="form-control" id="txtTo"
placeholder="end date(yyyy-mm-dd)" name="dateTo">
</div>
</div>
<div>
<br>
</div>
<div class="row">
<div class="row-2">
<input type="submit" class="btn btn-primary btn-sml"
value="check">
</div>
</div>
</form>
</div>
</div>
</div>
<div th:fragment="contentresult">
<div class="container-md">
<div class="row">
<div class="row">
<label style="color: black; font-weight: bold;">Issues: </label>
</div>
<br>
<div class="row">
<label for="Feedback"
th:text="'checking entries between '+ ${dateFrom}+' and '+ ${dateTo}"></label>
</div>
<div>
<textarea id="feedbackSection" name="story" cols="100" rows="10"
th:text="${styledErrors}">
</textarea>
</div>
</div>
<div>
<label th:if="${containsErrors}" style="color: green;"> There are
no issues. The entries can be imported</label>
<label
th:unless="${containsErrors}" style="color: red;"> There are
issues! Read the above for details</label>
</div>
<br>
<div class="row">
<div class="row-2">
<a th:if="${containsErrors}" type="button" th:attr="href='/importToDb'"
class="btn btn-primary btn-sml">Import</a>
<input th:unless="${containsErrors}" type="button" disabled="disabled"
value="Import">
</div>
</div>
</div>
</div>
<div th:fragment="contentmessage">
<div class="container-md">
<div class="row">
<label style="color: green; font-weight: bold;"
th:text="'Entries between '+ ${dateFrom}+' and '+ ${dateTo}+' are stored on the database'"></label>
</div>
</div>
</div>
</body>
</html>
I have run into a problem in my controller application for the import button. When I click on the import, I want to utilise the features that were used while clicking the button (check)
#GetMapping("/showform")
public String showForm(#RequestParam(value = "dateFrom", required = false) String dateFrom,
#RequestParam(value = "dateTo", required = false) String dateTo, Model model)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
if (dateFrom != null && dateTo != null && !dateFrom.isBlank() && !dateTo.isBlank()) {
logger.info("inside the datefrom dateto");
CheckManager wm = prepareConfiguration(dateFrom, dateTo);
model.addAttribute("containsErrors", wm.getErrors().isEmpty());
model.addAttribute("styledErros", wm.getFormattedErrors(wm.getErrors()));
model.addAttribute("dateFrom", dateFrom);
model.addAttribute("dateTo", dateTo);
return "showform-errors"; //shows the fragment with contentinput and contentResult
} else {
logger.info("inside the validationform");
return "showform"; //only contentinput( having 2 textboxes for dates and a button)
}
}
private CheckManager prepareConfiguration(String dateFrom, String dateTo)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
LocalDate from = LocalDate.parse(dateFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate to = LocalDate.parse(dateTo, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Request req = new Request("username", "password");
List<Entry> entrylist = req.getEntryList(from,to);
// I want this info entrylist to be used globally
return new CheckManager(entryList,from,to);
}
#GetMapping("/placeinDB")
public String placeInDb(Model model) {
logger.info("Inside the db import");
//HERE I WOULD LIKE TO USE THE DATES AND THE LIST I HAD IN THE ABOVE RETURN STATEMENT
}
Problem: When I hit the endpoint(/placeinDB) I do not have the resources like entryList, datefrom, dateTo to perform some modifications.
I am hoping there is some spring annotation that could help me here. Please let me know.

How to select two (or more) HTML elements that exist at the same tree level with Jsoup?

I'm working on a project and I faced a problem. I need to scrape data from the website that contains following HTML code:
<div class="lin-curso" style="border: 0;">
<div class="lin-area-c3">
Vagas 2017
</div>
</div>
<div class="box10">
<div class="lin-area-c1">
L160
</div>
<div class="lin-area-c2">
Acupuntura
</div>
<div class="lin-area-c3">
[Lic-1º cic]
</div>
</div>
<div class="lin-curso">
<div class="lin-curso-c1">
</div>
<div class="lin-curso-c2">
3155
</div>
<div class="lin-curso-c3">
Instituto Politécnico de Setúbal - Escola Superior de Saúde
</div>
<div class="lin-curso-c4">
20
</div>
</div>
<br>
<div class="box10">
<div class="lin-area-c1">
9059
</div>
<div class="lin-area-c2">
Administração e Gestão de Empresas
</div>
<div class="lin-area-c3">
[Lic-1º cic]
</div>
</div>
<div class="lin-curso">
<div class="lin-curso-c1">
</div>
<div class="lin-curso-c2">
2270
</div>
<div class="lin-curso-c3">
Universidade Católica Portuguesa - Faculdade de Ciências Económicas e Empresariais
</div>
<div class="lin-curso-c4">
n.d.
</div>
</div>
<br>
<div class="box10">
<div class="lin-area-c1">
8056
</div>
<div class="lin-area-c2">
Administração e Gestão Pública
</div>
<div class="lin-area-c3">
[Lic-1º cic]
</div>
</div>
<div class="lin-curso">
<div class="lin-curso-c1">
</div>
<div class="lin-curso-c2">
4275
</div>
<div class="lin-curso-c3">
Instituto Superior de Ciências da Administração
</div>
<div class="lin-curso-c4">
20
</div>
</div>
<br>
<div class="box10">
<div class="lin-area-c1">
8194
</div>
<div class="lin-area-c2">
Administração da Guarda Nacional Republicana
</div>
<div class="lin-area-c3">
[Mest Integ]
</div>
</div>
<div class="lin-curso">
<div class="lin-curso-c1">
</div>
<div class="lin-curso-c2">
7510
</div>
<div class="lin-curso-c3">
Academia Militar
</div>
<div class="lin-curso-c4">
n.d.
</div>
</div>
<br>
<div class="box10">
<div class="lin-area-c1">
9672
</div>
<div class="lin-area-c2">
Administração e Marketing
</div>
<div class="lin-area-c3">
[Lic-1º cic]
</div>
</div>
BOX10 and line-curso should form an element and they don't.
Because in some lines there is only one BOX10 for one Lin-curso but there are lines that are like Lin-curso for one Box10 , if Box10 and Lin-curso were an element there wouldn't be a problem , is there a way I can associate those two ?
EDIT: The website link is this : http://www.dges.gov.pt/guias/indcurso.asp?letra=A
And the element is the ".inside"
Solution to this problem is fairly easy when you use sibling selector. In your case div with class box10 plays role of a header in the table and sibling divs with class lin-curso play role of table data rows. I would suggest firstly selecting all divs with class box10:
Elements boxes = doc.select("div.box10");
Then you can iterate over boxes and do two major things:
Extract data you are interested in from this div (it contains 3 child nodes, divs with classes lin-area-c1, lin-area-c2 and lin-area-c3)
Select sibling nodes with class lin-curso and extract data from them.
Jsoup provides a method called Element.nextElementSibling() that return sibling element to the element you called this method on. So when you call it on element div.box10 you will get sibling element div.lin-curso.
Sibling in this case means a node immediately following the specified node at the same tree level.
Exemplary solution
Below you can find exemplary code that parses given website and prints table to the console output:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
final class TestMain {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("http://www.dges.gov.pt/guias/indcurso.asp?letra=A").get();
Elements boxes = doc.select("div.box10");
for (Element box : boxes) {
String linAreaC1 = box.select(".lin-area-c1").text();
String linAreaC2 = box.select(".lin-area-c2").text();
String linAreaC3 = box.select(".lin-area-c3").text();
System.out.printf("%s: %s %s%n", linAreaC1, linAreaC2, linAreaC3);
Element linCurso = box.nextElementSibling();
while (linCurso.hasClass("lin-curso")) {
String linCursoC2 = linCurso.select(".lin-curso-c2").text();
String linCursoC3 = linCurso.select(".lin-curso-c3").text();
String linCursoC4 = linCurso.select(".lin-curso-c4").text();
System.out.printf("%s\t%s\t%s%n", linCursoC2, linCursoC3, linCursoC4);
linCurso = linCurso.nextElementSibling();
}
System.out.println("==============================");
}
}
}
I hope it helps.

How to close modal dialog on web page using web driver - Java

I'm trying to close dialog that appears on a web page using mainly selenium web driver and Java but without any results. My code:
#When("^I am on second page I click on close button in pop up$")
public void i_am_on_second_page_I_click_on_close_button_in_pop_up() throws Throwable {
driver.findElement(By.xpath("//*[#id=\"ngdialog2\"]/div[2]/promo-banner/div/div/div[2]/div/dialog-body/div[1]/div[2]")).click();
driver.switchTo().activeElement();
I get:java.lang.NullPointerException
java.lang.NullPointerException
at SeconPage.i_am_on_second_page_I_click_on_close_button_in_pop_up(SeconPage.java:17)
at ✽.When I am on second page I click on close button in pop up(SeconPage.feature:7)
What I'm missing?
<div class="dialog-body">
<div ng-transclude="dialogBodySlot">
<dialog-body>
<div class="promo-popup-top">
<picture><img class="promo-popup-image"
ng-srcset="/etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-popup.png, /etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-popup#2x.png"
srcset="/etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-popup.png ,/etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-popup#2x.png">
</picture>
<div class="icon-115 promo-popup-icon-family"><img
ng-src="/etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-extra-logo.png"
src="/etc/designs/ryanair/frontend/resources/ui/illustrations/products/family-extra-logo.png">
</div>
<div class="promo-popup-close" ng-click="$ctrl.onClose()">
<core-icon class="icon-16 fill-c-light-base" icon-id="glyphs.close">
<div>
<svg tabindex="-1" focusable="false" role="img">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/pl/pl/#glyphs.close"
ng-href="/pl/pl/#glyphs.close"></use>
</svg>
</div>
</core-icon>
</div>
<div class="popup-message-shadow"><!----><p ng-if="::!$ctrl.firstName" class="first-message"
translate="common.components.family_extra_popup.message1"
translate-default="">Witaj!</p><!----><!----><h3
class="second-message" translate="common.components.family_extra_popup.message3"
translate-default=""><span class="yellow-text">Zaoszczędź </span>na kolejnej podróży dzięki
naszym super ofertom <span class="yellow-text">Family Extra</span></h3></div>
</div>
<div class="promo-popup-benefits family">
<ul class="family-benefits-list"><!---->
<li ng-repeat="benefit in ::$ctrl.popupBenefits track by $index" class="family-benefit">
<core-icon class="icon-40 family-benefit-icon"
ng-class="::$ctrl.popupResources.class + '-benefit-icon'" icon-id="baggage">
<div>
<svg tabindex="-1" focusable="false" role="img">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/pl/pl/#baggage"
ng-href="/pl/pl/#baggage"></use>
</svg>
</div>
</core-icon>
<span class="family-benefit-text" translate="common.components.family_extra_popup.benefit1"
translate-default="">50% zniżki na bagażu (15 kg) dzieci</span></li><!---->
<li ng-repeat="benefit in ::$ctrl.popupBenefits track by $index" class="family-benefit">
<core-icon class="icon-40 family-benefit-icon"
ng-class="::$ctrl.popupResources.class + '-benefit-icon'"
icon-id="priority-boarding">
<div>
<svg tabindex="-1" focusable="false" role="img">
<use xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:href="/pl/pl/#priority-boarding"
ng-href="/pl/pl/#priority-boarding"></use>
</svg>
</div>
</core-icon>
<span class="family-benefit-text" translate="common.components.family_extra_popup.benefit2"
translate-default="">50% zniżki na usługę Priority Boarding dla dzieci</span></li><!---->
<li ng-repeat="benefit in ::$ctrl.popupBenefits track by $index" class="family-benefit">
<core-icon class="icon-40 family-benefit-icon"
ng-class="::$ctrl.popupResources.class + '-benefit-icon'" icon-id="insurance-shield">
<div>
<svg tabindex="-1" focusable="false" role="img">
<use xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:href="/pl/pl/#insurance-shield" ng-href="/pl/pl/#insurance-shield"></use>
</svg>
</div>
</core-icon>
<span class="family-benefit-text" translate="common.components.family_extra_popup.benefit3"
translate-default="">50% zniżki na ubezpieczenie dla dzieci</span></li><!---->
<li ng-repeat="benefit in ::$ctrl.popupBenefits track by $index" class="family-benefit">
<core-icon class="icon-40 family-benefit-icon"
ng-class="::$ctrl.popupResources.class + '-benefit-icon'" icon-id="seat">
<div>
<svg tabindex="-1" focusable="false" role="img">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/pl/pl/#seat"
ng-href="/pl/pl/#seat"></use>
</svg>
</div>
</core-icon>
<span class="family-benefit-text"
translate="common.components.family_extra_popup.mandatory_seat_benefit"
translate-default="">Darmowe miejsca rezerwowane dla dzieci poniżej 12. roku życia</span>
</li><!----></ul>
<button class="core-btn-primary core-btn-phone-full" ng-click="$ctrl.onClose()"
translate="trips.biz_plus_popup.close" translate-default="">Kontynuuj wyszukiwanie
</button>
</div>
</dialog-body>
</div>
</div>
If the alert is definitely there then:
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
alert.dismiss();
}
If you have to wait for it to appear:
try {
WebDriverWait wait = new WebDriverWait(driver, 8);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//handle the exception
}
Try following and let me know whether it works for you:
#When("^I am on second page I click on close button in pop up$")
public void i_am_on_second_page_I_click_on_close_button_in_pop_up() throws Throwable {
driver.findElement(By.xpath("//*#id='ngdialog2']/descendant::div[#class='dialog-body']/descendant::div[#class='promo-popup-close']")).click();
driver.switchTo().activeElement();
( ( JavascriptExecutor ) _driver )
.executeScript( "window.onbeforeunload = function(e){};" );

Locating elements in <li> using selenium webdriver with java

I need to locate each item and click on it.
I tired this:
List<WebElement> allTournaments = driver.findElements(By.xpath("//*[#id='main-section']/div/div/section/div[1]/ul/li/div/div[1]/div"));
for (WebElement tournament : allTournaments) {
tournament.click();
}
But got the error "element not visible"
The xpath of first element is //[#id='main-section']/div/div/section/div1/ul/li1/div/div1/div
xpath of second element is //[#id='main-section']/div/div/section/div1/ul/li[2]/div/div1/div
like wise..
can anybody help..?
HTML:
<div class="header-toggle-area">
<div class="header-notification-area text-right ng-scope" ng-controller="notificationController">
</header>
<!--HEADER ENDS-->
<div class="content-wrap" style="padding-top: 60px;">
<aside id="main-sidebar">
<!--MAIN SIDEBAR ENDS-->
<main id="main-section">
<div class="main-content">
<div class="ng-scope" ng-controller="NewTournamentsController as tournaments">
<header class="member-title dt-title-main">
<section class="dashboard-tournaments-listing">
<div class="" ng-show="tournaments.Page==1">
<ul class="row dashboard-listing">
<!-- ngRepeat: running in tournaments.runningTournaments -->
<li class="dashboard-listing-items ng-scope" ng-repeat="running in tournaments.runningTournaments" style="">
<div class="dtslider-block">
<div class="dtslider-content">
<img ng-src="../../category/categoryDefault.jpg" alt="slider" src="../../category/categoryDefault.jpg"/>
<div class="hover-contents">
<div class="hc-timer">
<p> Tournament ends in </p>
<div class="hct-ticker ng-binding"> 04:30 - 26/11/16 </div>
</div>
<div class="hc-details">
<div class="hcd-block ng-hide" ng-show="running.JoinedPlayers>0">
<ul class="hc-icons">
</div>
</div>
</div>
Check if each element is visible and clickable as follows:
for (WebElement tournament : allTournaments) {
if (tournament.isDisplayed()
&& ExpectedConditions.elementToBeClickable(tournament).equals(true)) {
tournament.click();
}
}

Vaadin : CustomLayout don't generate <div> content

I'm using Vaadin 7. When I try to add html content to CustomLayout it does not generate a paragraph inside a div element. Here is the input :
<div style="margin-top: 10px; padding-left: 50px;" class="col-lg-10">
<div class="bs-component">
<ul class="nav nav-pills">
<li class="active"><a href="#Myprofile" class="active"
data-toggle="tab">Profile</a></li>
<li class="">setting</li>
<li class="">Tasks</li>
</ul>
<div class="tabbable">
<div class="tab-content">
<div id="Myprofile" location="Myprofile" class="tab-pane active"></div>
<div id="setting" location="setting" class="tab-pane">
<p>My paragraph</p>
</div>
</div>
</div>
</div>
In java I use this :
String html; //This var contain my input
InputStream is = new ByteArrayInputStream(html.getBytes());
CustomLayout custom = null;
try {
custom = new CustomLayout(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Finaly I add the customLayout to my mainLayout. When I run the application I get this output :
<div style="margin-top: 10px; padding-left: 50px;" class="col-lg-10">
<div class="bs-component">
<ul class="nav nav-pills">
<li class="active"><a href="#Myprofile" class="active"
data-toggle="tab">Profile</a></li>
<li class="">setting</li>
<li class="">Tasks</li>
</ul>
<div class="tabbable">
<div class="tab-content">
<div id="Myprofile" location="Myprofile" class="tab-pane active"></div>
<div id="setting" location="setting" class="tab-pane">
</div>
</div>
</div>
</div>
My paragraph inside div with id=setting was not generated by Vaadin. Any Ideas to fix this problem ?
I found the source of the problem. I removed the location="setting" part in the div element and it worked. I don't know why It does that. Probably because CustomLayout when generating the html looks for elements to put in the location, if it does not find one it clean all the element content.
Don't you need the location="setting" attribute? Don't you insert a component for that attribute?

Categories