Print multiple texts from multiple elements with same class name - javascript

Im trying to print all the product names from an e commerce website in selenium using java but its printing only the first name of the product from the first class it finds. How to print all the product names from all the classes with same class name?
This is my code:
package introduction;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Getproductnames {
private static int i;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.get("https://www.fipola.in/chicken");
driver.findElement(By.id("DelLocation")).sendKeys("600020");
driver.findElement(By.className("top_pincode_select")).click();
Thread.sleep(3000);
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i=0; i<products.size(); i++);
{
String[] names = new String[]{products.get(i).getText()};
System.out.println(names[i] + "");
}
}
}

You can use the below to print all the products name
List<WebElement> products=driver.findElements(By.cssSelector("a.product-item-link"));
for(int i =0;i<products.size();i++) {
String elementText = products.get(i).getText();
System.out.println(elementText);
}

Related

Error to access a .xls file in android studio

I've a file named "question.xls". I'm trying to generate a two dimensional string array with that sheet.I've add the jxl.jar as resource library.Here's my code and problem.Here's the MainActivity.java.I've just tried to acces each cell then assigning them into two dimensional array
package com.example.bhagyo.excell;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class MainActivity extends AppCompatActivity {
String[] str;
String zz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readQuestion();
}
private void readQuestion() {
try{
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("question.xls");
Workbook workbook = Workbook.getWorkbook(inputStream);
Sheet sheet = workbook.getSheet(0);
int k=0;
int row = sheet.getRows();
int col = sheet.getColumns();
Log.d("Result","table details: "+row+" "+col);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
Cell cell = sheet.getCell(j,i);
zz="";
if(j==5){
zz=zz+"Answer: "+(cell.getContents()).toString();
}
else if(j==0){
zz=(cell.getContents()).toString()+" ";
}
else{
zz=zz+" "+(cell.getContents()).toString();
}
}
str[k++]=zz;
Log.d("MyActivity","Dekhi "+zz);
}
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
}
My verbose log is full of empty the error is mainly caused bu null array but where is it
10-27 15:29:50.631 2719-2719/? D/Result: table details: 970 7
10-27 15:29:50.632 2719-2719/? D/AndroidRuntime: Shutting down VM
10-27 15:29:50.633 2719-2719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bhagyo.excell, PID: 2719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bhagyo.excell/com.example.bhagyo.excell.MainActivity}: java.lang.NullPointerException: Attempt to write to null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to write to null array
at com.example.bhagyo.excell.MainActivity.readQuestion(MainActivity.java:55)
at com.example.bhagyo.excell.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
You haven't initialized your str array. Initialize it after you define row:
int row = sheet.getRows();
str = new String[row];
That will get rid of the NullPointerException.
However, you're not creating a 2-dimensional array, either. You're creating a single-dimensional array with each index holding a single string containing the data of the last column only.
Change your code a bit:
Change
String[] str;
To
String[][] str;
Initialize it after initializing row and col:
int row = sheet.getRows();
int col = sheet.getColumns();
str = new String[row][col];
Then change your loops a bit:
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
Cell cell = sheet.getCell(j,i);
String column;
if (j == 5) {
column = "Answer: " + cell.getContents();
} else {
column = cell.getContents().toString();
}
str[i][j] = column;
}
}

Empty page using sendIntent.putExtras(bundle), page not filled Android studio

I'm trying to send some stuff via mail or Bluetooth etc but not working very well.
I would like to see a text like this:
" Respiration Rate: 0 2.0 5.0 16.0 "...
To do that I've implemented a button and Resut.java stuff. When I try to click on the button and I choose e-mail, app open a mail and the text is only "Respiration Rate"
here click-button:
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
result.java:
package com.google.android.gms.samples.vision.face.rPPG;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class RespirationResult extends AppCompatActivity {
private String Date;
int RR;
int il_risultato;
double [] plot_array;
int[] intArray;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date today = Calendar.getInstance().getTime();
private String[] RRtoSent=new String[300];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respiration_result);
Date = df.format(today);
TextView RRR = (TextView) this.findViewById(R.id.RRR);
ImageButton SRR = (ImageButton)this.findViewById(R.id.SendRR);
//-------------------------------------------------------------------------risutato
Bundle b = getIntent().getExtras();
double result = b.getDouble("key");
plot_array=b.getDoubleArray("array");
il_risultato=(int) Math.round(result);
RRR.setText(String.valueOf(il_risultato)); //prima era RR, da mettere successivamente
RRtoSent = new String[plot_array.length];
for (int i = 0; i < RRtoSent.length; i++) {
RRtoSent[i] = String.valueOf(plot_array[i]);
}
//grafico
GraphView graph;
LineGraphSeries<DataPoint> series; //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graphico);
series= new LineGraphSeries<>(data()); //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series); //adding the series to the GraphView
//series.setShape(PointsGraphSeries.Shape.POINT);
// activate horizontal and vertical zooming and scrolling
graph.getViewport().setScalableY(true);
graph.getGridLabelRenderer().setGridColor(Color.DKGRAY);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.DKGRAY);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.DKGRAY);
// graph.setTitle("Respiration Rate/min");
graph.getGridLabelRenderer().setHorizontalAxisTitle("time(sec)");
graph.getGridLabelRenderer().setVerticalAxisTitle("RR");
// set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0.5);
graph.getViewport().setMaxX(100);
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
public DataPoint[] data(){
DataPoint[] values = new DataPoint[plot_array.length]; //creating an object of type DataPoint[] of size 'n'
for(int i=0;i<plot_array.length;i++){
DataPoint v = new DataPoint(i,plot_array[i]);
values[i] = v;
}
return values;
}
#Override
public void onBackPressed() {
Intent i = new Intent(RespirationResult.this, SplashScreen.class);
startActivity(i);
finish();
super.onBackPressed();
}
}
Does anyone have an idea about it?
what's wrong or missing?
Thanks in advance
From Android official site:
public static final String EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent. Note that this may
be a styled CharSequence, so you must use Bundle.getCharSequence() to
retrieve it.
So you should convert your double array to String first before calling email app.
Step 1: Write a method which convert a double array to a string.
private String convertDoubleArrayToString(double[] array) {
StringBuilder sb = new StringBuilder();
for (double number: array) {
sb.append(number).append(" ");
}
return sb.toString();
}
Step 2: Change your code to
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " + convertDoubleArrayToString(plot_array));
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
That's because all you want to show must be part of the EXTRA_TEXT:
sendIntent.putExtra(Intent.EXTRA_TEXT, "EVERYTHING YOU WANT TO PRINT HERE" );
So you have to build a string with your data, then you create the extra with the complete string.

Can we give bulk url's in this code?

URL url = new URI("http://tamilblog.ishafoundation.org/").toURL();
I want to give 100 url in this connector?
I have the code to run single home page to extract its data
I need to get more contents From several links !
Is it any way possible ?
Here is my code
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class NewClass {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("http://tamilblog.ishafoundation.org").get();
Elements section = doc.select("section#content");
Elements article = section.select("article");
for (Element a : article) {
System.out.println("Title : \n" + a.select("a").text());
System.out.println("Article summary: \n" + a.select("div.entry-summary").text());
}
}
}
I got output from this single page Now i need to get it from several pages (100+links) at once.
And to save it in a document.

Drag and drop testing in selenium on html5 (Using java)

This is my first question ever so please go light on me. I am trying to test the drag and drop feature on HTML5 using selenium and java as my main language. However I am fully aware that it is not supported by selenium webdriver itself but there is a workaround on the stackoverflow forum where a user used a javsacript file to simulate the drag and drop action.
The link to that javascript workaround is HERE
I have tried to follow the instructions but since i am quite new to coding, I am wasting my time messing around. However, I have tried my best but now i am having problems with loading scripts. Thanks.
(Turned out that I was not correctly executing the drop.js script. The working code is below:)
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class check {
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.Firefox.driver", "Path_executable");
WebDriver driver= new FirefoxDriver();
driver.get("http://html5demos.com/drag#");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
String filePath = "C://drop.js";
String source = "#one";
String target = "#bin";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);
String javaScript = buffer.toString();
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}
My code is:-
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import javax.script.ScriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class drag {
public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
System.setProperty("webdriver.Firefox.driver", "Address_Executable");
WebDriver driver = new FirefoxDriver();
driver.get("http://html5demos.com/drag");
final String JQUERY_LOAD_SCRIPT = ("C:\\jQuerify.js");
String jQueryLoader = readFile(JQUERY_LOAD_SCRIPT);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(
jQueryLoader /* , http://localhost:8080/jquery-1.7.2.js */);
// ready to rock
js.executeScript("jQuery(function($) { " + " $('input[name=\"q\"]').val('bada-bing').closest('form').submit(); "
+ " }); ");
final String DROP = ("C:\\drop.js");
String scriptLoader = readFile(DROP);
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript(
scriptLoader /* , http://localhost:8080/jquery-1.7.2.js */);
((JavascriptExecutor) driver).executeScript(js1 + "$('#one').simulateDragDrop({ dropTarget: '#bin'});");
}
private static String readFile(String file) throws IOException {
Charset cs = Charset.forName("UTF-8");
FileInputStream stream = new FileInputStream(file);
try {
Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
return builder.toString();
} finally {
stream.close();
}
}
}

Jasper Report : "Document has no pages"

I have a problem when I run this code. I get always this message : "Document has no pages" with a blank page in the pdf file .
Note: I'm using NetBeans IDE 7.2 Beta.
Jar files imported are:
com.lowagie.text-2.1.7.jar
commons-beanutils-1.5.jar
commons-collections-2.1.jar
commons-digester-2.1.jar
commons-javaflow.jar
commons-logging-1.3.jar
jasperreports-5.5.1.jar
javax.servlet.jar
I need your help,please.
this is my code :
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Currency;
import java.util.HashMap;
import javax.swing.JFrame;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
public class Report extends JFrame{
public Report(String month,int year){
try{
//load the driver
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/motor";
String user="root";
String pass="";
Connection cn=DriverManager.getConnection(url,user,pass);
System.out.println("connected in report");
PreparedStatement ps = cn.prepareStatement("select number,title,name,ikar,echtirak,price,tarakom from users order by number asc");
ResultSet rs;
rs=ps.executeQuery();
JasperPrint jasperPrint=null;
HashMap<String, Object> mapParameters = new HashMap <String, Object>();
// jrxml compiling process
JasperReport jasperReport = JasperCompileManager.compileReport("C:/Users/user/Documents/NetBeansProjects/MotorApp/MyReports/motorReport.jrxml");
int i=1;
while(rs.next()){
mapParameters.put("Name", rs.getString("title")+" "+rs.getString("name"));
mapParameters.put("Number",rs.getString("number"));
mapParameters.put("Ikar",rs.getString("ikar"));
mapParameters.put("Amperage",rs.getString("echtirak")+" A");
mapParameters.put("tarakom",rs.getString("tarakom")+" $");
mapParameters.put("monthPrice",rs.getString("price")+" $");
Integer total=Integer.parseInt(rs.getString("price"))+Integer.parseInt(rs.getString("tarakom"));
mapParameters.put("totalPrice",total+" $");
mapParameters.put("monthYear",year+" "+month);
try{
System.out.println("Filling report...");
jasperPrint = JasperFillManager.fillReport(jasperReport, mapParameters,cn);
JRViewer viewer = new JRViewer(jasperPrint);
System.out.println("Done!");
JasperExportManager.exportReportToPdfFile(jasperPrint,"C:/Users/user/Desktop/"+month+" "+year+".pdf");
}catch(JRException elle){
System.out.println(elle.getMessage());
}
}
}catch(Exception ev){
System.out.println(ev.getMessage());
}
}
}
I truly appreciate your help.
My first thought is on the motorReport.jrxml file. It may have some issues on its content. Try reducing the contents of the report to a point where the code works and the reports can display properly. It may give you a clue to the cause of the problem. Then get back here with more specifics if you still can't solve this problem.
mapParameters in your code is not records of DataSource. It is parameters of report, therefore report haven't records.
One of the possible solutions: convert ResultSet into BeanCollection, make JRBeanCollectionDataSource and pass it into fillReport.
Make bean for saving result of query.
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
....
}
For example result is
List myList = new ArrayList<UserBean>();
Convert into collection example here stackoverflow.com/questions/17206523/put-resultset-values-into-collection-object-then-add-to-arraylist
After convert you must call fillReport like this:
jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String,Object>, new JRBeanCollectionDataSource(myList));

Categories

Resources