i am not able to read the email id from the webpage below :
URL : https://targetstudy.com/university/2/acharya-ng-ranga-agricultural-university/
Here is my code
driver.navigate().to(URL);
String Email = driver.findElement(By.xpath("//*[#id="site-canvas"]/div[6]/div[2]/div[1]/div/div[1]/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td[2]/img")).getText();
System.out.println(Email);
Selenium alone can't help you in this case, though your binding language would help you.
You need Java Tesseract API.
Code for extracting text :
public String getImgText(String imageLocation) {
ITesseract instance = new Tesseract();
try
{
String imgText = instance.doOCR(new File(imageLocation));
return imgText;
}
catch (TesseractException e)
{
e.getMessage();
return "Error while reading image";
}
}
If you are using maven for your Project, just add this dependency :
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>3.2.1</version>
</dependency>
More Reference : Extracting text from Image
Related
I'm working on a spring boot project using thymeleaf
I need to create a Word file (.docx) based on an existing one (as a template) that contains styles, tables, images... , and also I need to modify and customize some lines at the same time.
I checked some codes and answers about the Apache POI Library but nothing works for my case.
Any ideas PLEASE!
Thanks and regards
I solved my problem using this code :
public void wordFileCreator() throws IOException
{
String filename = "Template.docx";
try {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
List<XWPFParagraph> paragraphList = doc.getParagraphs();
for (XWPFParagraph para : paragraphList) {
for (XWPFRun run : para.getRuns()) {
String text = run.text();
if(text.contains("StringToReplace")){
text = text.replace("StringToReplace", "newVal");
run.setText(text, 0);
}
}
}
doc.write(new FileOutputStream("newFile.docx"));
} catch (Exception e) {
e.printStackTrace();
}
}
Base64 image in selenium extent report is not displayed correctly after clicking the image in the report.
Searched various sources to get the issue resolution but did not find the answer anywhere
//dependency in POM.xml Code:-
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.1.5</version>
</dependency>
//ExtentReporterListener Code :-
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail("Test failed due to below error");
try {
test.get().fail(result.getThrowable(), MediaEntityBuilder.createScreenCaptureFromPath(TestUtil.getScreenshotExtent()).build());
} catch(IOException e) {
System.err.
println("Exception thrown while updating test fail status " + Arrays.toString(e.getStackTrace()));
}
test.get().getModel().setEndTime(getTime(result.getEndMillis()));
}
//Capture screenshots code:-
public class TestUtil {
public static String getScreenshotExtent() {
String Base64StringofScreenshot = "";
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
byte[] fileContent;
try {
fileContent = FileUtils.readFileToByteArray(src);
Base64StringofScreenshot = "data:image/png;base64," + Base64.getEncoder().encodeToString(fileContent);
} catch(IOException e) {
e.printStackTrace();
}
return Base64StringofScreenshot;
}
}
Can someone please help how to resolve this issue and correctly display the image in extent report after clicking it?
can you please let me know in which browser you are running this Automation suite?
for e.g: You are using Chrome browser in windows OS 64 bit, then you need to check the chromedriver.exe which you have downloaded, that is for 32 bit or 64 bit.If you are using the driver for 32 bit then this type of issue comes.
If you are still not finding any solution then let me know.
I want to develop an application who can send direct messages look this:
public static void sendDirectMessage(Long recipientId, String message){
System.out.print("[Bot] Sending message to #"+recipientId+"... ");
try {
twitter.sendDirectMessage(recipientId, message);
System.out.println("done");
} catch (TwitterException e) {
System.out.println("fail");
e.printStackTrace();
System.err.println("[Error] "+e.getErrorMessage());
}
}
I call to this statement with:
private static String
customer_key = "",
Oth_key = "",
access_token = "",
access_key = "";
private static TwitterBot bot;
public static void main(String[] args) {
try {
bot = new TwitterBot(customer_key, Oth_key, access_token, access_key);
} catch (TwitterException e) {
e.printStackTrace();
} catch (InterruptedException e) {
System.err.println("[Err] "+e.getMessage());
}
bot.sendDirectMessage(bot.getUserData("AbA2L1").getId(), "Message test:!");
}
it's return error:
404:The URI requested is invalid or the resource requested, such as a user, does not exists. Also returned when the requested format is not supported by the requested method.
message - Sorry, that page does not exist.
code - 34
Note:
The functions search(), getHomeTimeline() and updateStatus() works.
I have activated Read, Write and Direct messages on twitter application permissions.
sorry for my bad english.
It's work with this vertion, add it into pom.xml file:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.twitter4j/twitter4j-core -->
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.7</version>
</dependency>
</dependencies>
Good luck.
Which version of Twitter4J are you using? The new Direct Message API is only a few weeks old so you may need a new version.
Use Twitter4j-core-4.0.7 version for Direct Message Functionality of Twitter.
Other Version of Twitter4j Library shows TwitterException of User Not Found or Page Does not exist.
Hey guys I am working on a load class for my project that loads and pulls a info from a xml files. I have been following a few guides online but I am running into the error java.lang.NoClassDefFoundError: org/jaxen/JaxenException. I know the code is finding the save file because I can print out the name. But when I try to pull out the info I get that error. Snippet of code is below if there is no error in there let me know and Ill post more.
public void LoadProjects()
{
try
{
Files.walk(Paths.get("D:/workspace/Project Program/Projects/")).forEach(filePath ->
{
if(Files.isRegularFile(filePath))
{
System.out.println("Testing");
try
{
SAXReader reader = new SAXReader();
Document document = reader.read(filePath.toFile());
System.out.println(document.getName());
Node node = document.selectSingleNode("///Project/Info");
//String name = node.valueOf("#Name");
//String projNum = node.valueOf("#ProjectNumber");
//node = document.selectSingleNode("//Project/Dates");
//String dueBy = node.valueOf("#DueBy");
//CButton temp = new CButton(name, projNum, dueBy);
//Console.console.AddToList(temp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Did you add the jaxen jar to your servers lib?
Your code seems correct so far but please add as much information as possible from the beginning.
Ff you are using maven:
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
I am looking for a way to attach a screenshot to Results section of TestNG Report for the failed methods.
So far I was able to attache my screenshots to Reporter Output by implementing this:
Reporter.log("<br> <img src=.\\screenshots\\" + fileName + " /> <br>");
but still struggling with adding them to Test Results section of failed methods.
I was able to implement Listener and intercept onTestFailure actions which was originally suggested here:
How can I include a failure screenshot to the testNG report
Here is an example of that:
#Override
public void onTestFailure(ITestResult result) {
Reporter.setCurrentTestResult(result);
Reporter.log("<br> <img src=.\\screenshots\\Untitled.png /> <br>");
Reporter.setCurrentTestResult(null);
}
But Reporter.log function still pushes my information in the Reporter output log but not in the Results->Failed methods->Failed method log.
Update (03/14/14): I've attached screenshot to clarify my question. The problem is not in capturing screenshot and attaching it to Report. That part works fine. The problem is that screenshot is attached to Test Output part of the report but I want to see it in Results -> Failed Methods.
I have also implemented the same extending Testng TestListenerAdapter. By capturing the screenshot then attach it to the Testng Report with the image of size height=100 and width=100 with onTestFailure. Please see below if this helps solve your problem
File scrFile = ((TakesScreenshot) WebdriverManager.globalDriverInstance).getScreenshotAs(OutputType.FILE);
//Needs Commons IO library
try {
FileUtils.copyFile(scrFile, new File(file.getAbsolutePath()+ "/selenium-reports/html/" + result.getName() + ".jpg"));
Reporter.log("<a href='"+ file.getAbsolutePath()+"/selenium-reports/html/" + result.getName() + ".jpg'> <img src='"+ file.getAbsolutePath()+"/selenium-reports/html/"+ result.getName() + ".jpg' height='100' width='100'/> </a>");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Reporter.setCurrentTestResult(null);
In addition to above don't forget to add following lines to your testng suite xml
<listeners>
<listener class-name="com.tests.DotTestListener" />
</listeners>
OR
passing as listner parameter if you are executing it from command line
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener com.tests.DotTestListener test\testng.xml
Reference : http://testng.org/doc/documentation-main.html#logging-listeners
I've had same problem but it solved. By implementing SuitePanel you will be able to add screenshot as you want
https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/jq/SuitePanel.java
I almost don't change the original code except
...
// Description?
String description = tr.getMethod().getDescription();
if (! Strings.isNullOrEmpty(description)) {
xsb.push("em");
xsb.addString("(" + description + ")");
xsb.pop("em");
}
// Add screen shot here
xsb.push(“img”,”src”,imagePath);
xsb.pop(“img”);
xsb.pop(D);
xsb.pop(D);
If you want to show the screen shot on the failed method then you will have to capture the exception and modify its message content and add img html to that and then it will appear. Let me know if you need example
I had same issue but its fixed now. I made a method to catcher screenshot in base class. this method return full path of screenshot.
public String getScreenshot (String screenshotName, WebDriver driver) throws IOException{
DateFormat dateformate = new SimpleDateFormat("dd-mm-yy-hh-mm-ss");
Date date = new Date();
String currentdate = dateformate.format(date);
String imageName =screenshotName+currentdate;
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String location =System.getProperty("user.dir")+"\\testOutput\\screenshot\\"+imageName+".png";
File screenshotLocation =new File (location);
FileUtils.copyFile(source, screenshotLocation);
return location;
}
Add use this path to add screenshot in testng report as well as report log by updating testng TestNgListener-
public void onTestFailure(ITestResult arg0) {
Object currentClass = arg0.getInstance();
WebDriver driver = ((BrowserSetup) currentClass).getDriver();
String name = arg0.getName();
System.out.println(name);
try {
String screenshotPath =getScreenshot(name, driver);
System.out.println("Screenshot taken");
String path = "<img src=\"file://" + screenshotPath + "\" alt=\"\"/>";
System.out.println(screenshotPath+" and path - "+path);
Reporter.log("Capcher screenshot path is "+path);
} catch (Exception e) {
System.out.println("Exception while takescreenshot "+e.getMessage());
}
printTestResults(arg0);
}
I suggest you to use ReportNG instead of the primitive TestNG reports.
If the problem only with getting screenshots, you can try to get it like this:
private static byte[] GetCropImg(IWebDriver targetChrome, IWebElement targetElement)
{
var screenshot = ((ITakesScreenshot)targetChrome).GetScreenshot();
var location = targetElement.Location;
using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
{
var rect = new Rectangle(location.X, location.Y, targetElement.Size.Width, targetElement.Size.Height);
using (Bitmap bmpImage = new Bitmap(stream))
{
using (Bitmap cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat))
{
using (MemoryStream ms = new MemoryStream())
{
cropedImag.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
return byteImage;
}
}
}
}
}
and then you can save file or save sting64
var imgString64 = Convert.ToBase64String(byteImage); //Get Base64
PS: on JAVA it should be almost the same)
you can get failed test cases screen shots with name of failed test class by using #After method.
Use below code segment