How to read canvas element attribute value using selenium? - selenium

I want to read canvas element value ("Answer:5015") but attribute value does not exist. Can you please let me know how to read attribute value ?
App URL : https://the-internet.herokuapp.com/challenging_dom#edit

This code works, using Java and Edge browser:
System.setProperty("webdriver.edge.driver", "msedgedriver.exe");
WebDriver driver = new EdgeDriver();
driver.get("https://the-internet.herokuapp.com/challenging_dom#edit");
String answer = new String();
ArrayList<WebElement>scripts = new ArrayList<WebElement>((ArrayList<WebElement>) driver.findElements(By.tagName("script")));
for(int i = 0; i < scripts.size(); i++) {
String focusText = scripts.get(i).getAttribute("innerHTML");
if(focusText.contains("canvas.strokeText")) {
answer = focusText.substring(focusText.indexOf("Answer"), focusText.indexOf("',"));
break;
}
}
System.out.println(answer);

Related

Appium - not able to get the child element

preconditions:
PL: Java
java client 7.0.0
Appium server version: 1.13.0
Device Samasung Galaxy S
Android Version 9.0
Hello All,
I am trying since a day to get the error text field in email field in screen shot below, but I am not able to get this.
I have already tried the following :
1. actual_textInputError = driver.findElementByXPath("//android.widget.LinearLayout//android.widget.RelativeLayout//android.widget.RelativeLayout//android.widget.LinearLayout//android.widget.FrameLayout//android.widget.LinearLayout//android.widget.FrameLayout//android.widget.TextView").getText();
2. List<MobileElement> elements = driver.findElements(By.id("textinput_error"));
for (MobileElement element : elements) {
actual_textInputError = element.getText();
3. actual_textInputError = email_Field.findElementByClassName("android.widget.TextView").getText();
// List <MobileElement> rel_Layouts = driver.findElementsByXPath("*//android.widget.RelativeLayout");
4. MobileElement layout = (MobileElement)driver.findElementByXPath("//android.widget.RelativeLayout[contains(#resource-id, 'emailInput')]");
List <MobileElement> errors = driver.findElementsById("textinput_error");
actual_textInputError = errors.get(0).getText();
actual_textInputError = errors.get(1).getText();
actual_textInputError = errors.get(2).getText();
// MobileElement email_error_field = layout.findElementByXPath("//android.widget.RelativeLayout[contains(#resource-id, 'textinput_error'");
// actual_textInputError = email_error_field.getText();
/* for (int i = 0; i<errors.size();i++ ) {
actual_textInputError = errors.get(0).getText();
}*/
/* for (MobileElement rel_Layout : rel_Layouts) {
actual_textInputError = element.getText();
System.out.println("error text = " + actual_textInputError);
}*/
// actual_textInputError = driver.findElementsByXPath("//android.widget.RelativeLayout//android.widget.TextView").get(0);
// errorMessage_Text
//actual_textInputError = errorMessage_Text.getText();
is possible that some one send me the Xpath to search.
many Thanks in advance
Kindly use the below XPath.
//android.widget.TextView[#text='E-mail address is already in use']

How can I print all the submenu of main menu in webdriver

I want to print the submenu text of mainmenu of first list[Electronics] of
in selenium webdriver.
url : https://www.flipkart.com
But there is some issue to take the xpath of that sumMenu.
How can I take the xpath and all.
You can try with the following x-path to get all sub menus of main menu "Electronics"
//span[.='Electronics']/following-sibling::ul//li/a
Try the bellow code. Change value the String searchSubMenu = "Electronics"; if you want get text other sub menu, hope this helps.
driver.get("https://www.flipkart.com/");
//wait login popup and click
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#class='_2AkmmA _29YdH8']")));
driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
String searchSubMenu = "Electronics";
int totalSubMenu = driver.findElements(By.xpath("//*[contains(#class,'Wbt_B2')]")).size();
System.out.println("Search for : " +searchSubMenu);
for(int i=1; i<=totalSubMenu; i++) {
String getTextSubMenu = driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).getText();
System.out.println("Get Sub Menu Title : "+ getTextSubMenu);
if (getTextSubMenu.equals(searchSubMenu)) {
driver.findElement(By.xpath("(//*[contains(#class,'Wbt_B2')])[" +i +"]")).click();
Thread.sleep(1000);
String targetAllGetText = driver.findElement(By.xpath("(//*[contains(#class,'_3GtRpC')])[" +i +"]")).getText();
System.out.println(targetAllGetText);
break;
}
}
driver.quit();
It will help you : Please try
String SubMenu = driver.findElement(By.xpath("Xpath of element")).getText();
System.out.println(SubMenu);
if you want Size:
int Size =driver.findElement(By.xpath("Xpath of element"));
System.out.println(Size);

How to write locator for text between div and span (Preferably xpath) which contains non-breaking space (&nbsp)

I want to write xpath for the following div:
<div class='someclass' id='someid'>:TEST SELENIUM 1234<div>
Please note :
tag can be anything such as div, span ,or anchor tag.
can be present anywhere in the text.
What I have tried so far :
//div[contains(text(),":TEST SELENIUM 1234")]
//div[contains(text(),":TEST{ }SELENIUM{ }1234")]
//div[contains(text(),":TEST SELENIUM 1234")]
//div[normalize-space(text()) = ':TEST SELENIUM 1234']
//div[normalize-space(text()) = ':TEST{ }SELENIUM{ }1234']
//div[normalize-space(text()) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST{ }SELENIUM{ }1234']
//div[normalize-space(.) = ':TEST SELENIUM 1234']
//div[normalize-space(.) = ':TEST{\u00a0}SELENIUM{\u00a0}1234']
//div[normalize-space(.) = ':TEST${nbsp}SELENIUM${nbsp}1234']
What has worked for me (thanks to #Andersson)
//div[starts-with(text(), ":TEST") and substring(text(), 7)="SELENIUM" and substring(text(), 16)="1234"]
This is more of a work around and would work only for known Strings.
These are the SO post which I have already followed :
Link1
Link2
Any help will be highly appreciated.
According to the conversation above, you can use this sample xPath builder(JAVA):
public class Test {
public static void main(String[] args) {
String s = ":TEST SELENIUM 1234";
String[] parts = s.split(" ");
StringBuilder xpath = new StringBuilder("//*");
for (int i = 0; i < parts.length; i++){
xpath.append((i == 0) ? "[contains(text(), '" + parts[i] + "')" : " and contains(text(), '" + parts[i] + "')");
}
xpath.append("]");
System.out.println(xpath);
}
}
Output:
//*[contains(text(), ':TEST') and contains(text(), 'SELENIUM') and contains(text(), '1234')]
In Python I would do
required_div = [div for div in driver.find_elements_by_xpath('//div') if div.text == ':TEST SELENIUM 1234'][0]
to find required node by its complete text content ignoring non-breaking space chars
P.S. Again it's just a workaround, but it seem to be quite simple solution

Java - Want to produce a list of returned google search url's and then match them to a different url to find a hit - Selenium

I'm trying to create a program that will search keywords in google and then match the search results with a website url and if the url matches it will save the page and position on page in which that url was found. However, whenever I print the size of the list it returns 0
code:
driver.get("http://www.google.com");
element = driver.findElement(By.id("lst-ib"));
element.sendKeys(keyword);
element.sendKeys(Keys.RETURN);
int page = 0;
HashMap<Integer, Integer> hitList = new HashMap<Integer, Integer>();
for(int i=page;i<=pageNo;i++) {
List<WebElement> list = driver.findElements(By.className("_Rm"));
System.out.println(list.size());
Thread.sleep(10000);
for(int j=0;j<list.size();j++) {
String site = list.get(j).getText();
if(site.contains(website)) {
hitList.put(i, j);
}
driver.findElement(By.xpath(".//*[#id='pnnext']/span[2]")).click();
Thread.sleep(10000);
}

jmeter testcases which can handle captcha?

We are trying to build a jmeter testcase which does the following:
login to a system
obtain some information and check whether correct.
Where we are facing issues is because there is a captcha while logging into the system. What we had planned to do was to download the captcha link and display, and wait for user to type in the value. Once done, everything goes as usual.
We couldnt find any plugin that can do the same? Other than writing our own plugin, is there any option here?
I was able to solve it myself. The solution is as follows:
Create a JSR223 PostProcessor (using Groovy)
more practical CAPTCHA example with JSESSIONID handling and proxy setting
using image.flush() to prevent stale CAPTCHA image in dialog box
JSR223 Parameters for proxy connection setting:
Parameters: proxy 10.0.0.1 8080
In it, the following code displays the captcha and waits for user input
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
URL urlTemp ;
urlTemp = new URL( "https://your.domainname.com/endpoint/CAPTCHACode");
HttpURLConnection myGetContent = null;
if(args[0]=="proxy" ){
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(args[1], Integer.parseInt(args[2])));
myGetContent = (HttpURLConnection) urlTemp.openConnection(proxy);
}else{
myGetContent = (HttpURLConnection) urlTemp.openConnection();
}
// false for http GET
myGetContent.setDoOutput(false);
myGetContent.connect();
int status = myGetContent.getResponseCode();
log.info("HTTP Status Code: "+Integer.toString(status));
if (status == HttpURLConnection.HTTP_OK) {
//We have 2 Set-Cookie headers in response message but 1 Set-Cookie entry in Map
String[] parts2;
for (Map.Entry<String, List<String>> entries : myGetContent.getHeaderFields().entrySet()) {
if( entries.getKey() == "Set-Cookie" ){
for (String value : entries.getValue()) {
if ( value.contains("JSESSIONID") == true ){
String[] parts = value.split(";",2);
log.info("Response header: "+ entries.getKey() + " - " + parts[0] );
JMeterContext context = JMeterContextService.getContext();
CookieManager manager = context.getCurrentSampler().getCookieManager();
parts2 = parts[0].split("=",2)
Cookie cookie = new Cookie("JSESSIONID",parts2[1],"your.domainname.com","/endpoint",true,0, true, true, 0);
manager.add(cookie);
log.info( cookie.toString() );
log.info("CookieCount "+ manager.getCookieCount().toString() );
}
}
}
}//end of outer for loop
if ( parts2.find() == null ) {
throw new Exception("The Response Header not contain Set-Cookie:JSESSIONID= .");
}
}else{
throw new Exception("The Http Status Code was ${status} , not expected 200 OK.");
}
BufferedInputStream bins = new BufferedInputStream(myGetContent.getInputStream());
String destFile = "number.png";
File f = new File(destFile);
if(f.exists() ) {
boolean fileDeleted = f.delete();
log.info("delete file ... ");
log.info(String.valueOf(fileDeleted));
}
FileOutputStream fout =new FileOutputStream(destFile);
int m = 0;
byte[] bytesIn = new byte[1024];
while ((m = bins.read(bytesIn)) != -1) {
fout.write(bytesIn, 0, m);
}
fout.close();
bins.close();
log.info("File " +destFile +" downloaded successfully");
Image image = Toolkit.getDefaultToolkit().getImage(destFile);
image.flush(); // release the prior cache of Captcha image
Icon icon = new javax.swing.ImageIcon(image);
JOptionPane pane = new JOptionPane("Enter Captcha", 0, 0, null);
String captcha = pane.showInputDialog(null, "Captcha", "Captcha", 0, icon, null, null);
captcha = captcha.trim();
captcha = captcha.replaceAll("\r\n", "");
log.info(captcha);
vars.put("captcha", captcha);
myGetContent.disconnect();
By vars.put method we can use the captcha variable in any way we want. Thank you everyone who tried to help.
Since CAPTHA used to detect non-humans, JMeter will always fail it.
You have to make a workaround in your software: either disable captcha requesting or print somewhere on page correct captcha. Of course, only for JMeter tests.
Dirty workaround? Print the captcha value in alt image for the tests. And then you can retrieve the value and go on.