Selenium sendkeys enter pipe ( | ) for backslash (\) - selenium

In selenium sendkeys sometimes the backslash ( \ ) is replaced with a pipe ( | ) symbol. this issue is a sporadic issue.
Below is the code snippet that i have used
aItDriver.switchTo().window("[TITLE:Choose File to Upload]");
aItDriver.getKeyboard().sendKeys(new String[]{"I:\Downloads\fileName.txt" + Keys.ENTER});
in here we used autoit (aItDriver) driver to enter the file path for file upload screen,
expected output for the file upload screen was :
I:\Downloads\fileName.txt
But we see the below text entered to the upload window text box in rare cases.
I:|Downloads\fileName.txt
Could someone give an explanation to this sporadic issue, and if there is a correct way to enter the given text or fix for this issue?

#Marlan
depending on the language that you use, there is few solutions to fix the absolute path.
In java you can try:
public static void main(String[] args) throws IOException {
Path path = Paths.get("myFile.txt");
Path absolutePath = path.toAbsolutePath();
System.out.println(absolutePath.toString());
}
After that you can just used element.sendKeys(absolutePath.toString());
to upload file
Using JavaScript:
const path = require('path');
let absoluteFilePath = path.resolve('myFile.txt');
element(by.id('something').sendKeys(absoluteFilePath);

Related

it didn't work while i replace $cdc_lasutopfhvcZLmcfl to anything try to avoid detected by some site via chromedriver.exe

i had read this page Can a website detect when you are using selenium with chromedriver? and i follow the steps in that, but when i finish replace $cdc_lasutopfhvcZLmcfl to whatever_var , i can't lunch chrome by the driver edited, when i try to lunch it i got an error like this The application was unable to start correctly (0xc000007b)
it's that because the driver version i used with ChromeDriver 2.36.540470 ?
when i edit driver in vim after searching the var $cdc_lasutopfhvcZLmcfl,
i find the source code was different with the page i mentioned before, it look like this:
function getPageCache(opt_doc, opt_w3c) {
var doc = opt_doc || document;
var w3c = opt_w3c || false;
var key = '$cdc_asdjflasutopfhvcZLmcfl_';
if (w3c) {
if (!(key in doc))
doc[key] = new CacheWithUUID();
return doc[key];
} else {
if (!(key in doc))
doc[key] = new Cache();
return doc[key];
}
}
any suggestion please ?
When replacing '$cdc_lasutopfhvcZLmcfl', you must make sure to replace it with a string of the same length (and probably the same structure too). So, you would want to use a replacement that would look like this: '$sws_01234567890123456'. All together, 17 chars after the underscore.

Photoshop script suddenly stopped working - Error 8000

So I made a script for Photoshop based on this generator
The important part is
#target photoshop
function main() {
// prompt user to select source file, cancel returns null
var sourceFile = File.openDialog("Select a 1:1 sqaure PNG file that is at least 618x618.", "*.png", false);
if (sourceFile == null) {
// user canceled
return;
}
var doc = open(sourceFile, OpenDocumentType.PNG);
if (doc == null) {
alert("Oh shit!\nSomething is wrong with the file. Make sure it is a valid PNG file.");
return;
}
....
}
main();
this allways worked. But when today I wanted to change something in the script (I haven't even started yet and not used it for about 2 weeks) I suddendly only get an error (translated from german):
Error 8000: The file can not be opened since the parameters for opening are incorrect.
Line:764
-> doc = open(sourceFile, OpenDocumentType.PNG);
How can I open a PNG file via a File.Open dialog in a Photoshop script?
I already tried to add the app
var doc = app.open(sourceFile, OpenDocumentType.PNG);
to remove the document type specifier
var doc = open(sourceFile);
or to add this as I saw it in many forums
var doc = open(sourceFile, OpenDocumentType.PNG, undefined);
and variations between them. Nothing helped so far.
For debugging I also added
alert(sourceFile);
before the according line and get e.g.
~/Desktop/Example/originalImage_2000x2000.png
The problem apparently was with Photshop in general!
When I opened Photshop I didn't even get the default view of last opened files etc and actually was not able to open any file ... but never tested this first.
After rebooting the PC and launching Photshop now everything went back to normal and the script just runs fine and as expected.

Selenium to click Images link on Google and click first image

I have the below code. When I execute this,
Firefox opens - Expected
Go to Google.com - Expected
Keys in Pluralsight logo on searchbox - expected
I do not know what happens then I see the Google.com page with no text in searchbox.
However, when I put breakpoint and step in line by line I see it clicks Images. So, what is wrong when I execute it without breakpoints?
Another question I have is, once I am on the Images screen, how do I make my script click on the 1st image? I see the class name is rg_ic rg_i but I cannot use this as it has spaces. The ID keeps changing everytime. So, how can I click the 1st image? I commented it for now because I cannot get it to work.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Url = "http://google.com";
var searchBox = driver.FindElement(By.Name("q"));
searchBox.SendKeys("Pluralsight logo");
searchBox.Submit();
var imageLink = driver.FindElement(By.LinkText("Images"));
imageLink.Click();
//var firstImage = driver.FindElements(By.ClassName("rg_ic"))[0];
//firstImage.Click();
}
}
}
the image id's are constant, and I ran a successful test using this (granted I'm using python, but the syntax is similar):
driver.get("http://google.com")
search_box = driver.find_element_by_name("q")
search_box.send_keys("Pluralsight logo")
search_box.submit()
time.sleep(4)
first_img = driver.find_element_by_id("dimg_1").click()
You have to provide time for the image to load. You could do this with an expected condition or just an explicit wait. Hope this helps.

ExtentReports in Selenium Webdriver

I'm having an issue where ExtentReports is not showing the screenshot when the report is viewed on another machine. When saving the image into the report, I pass the absolute path of the image file. The user who wants to view the report have to copy report.html and Errorscreenshot folder to their D drive. Then only they can see the screenshot. Please suggest another way so that user can copy these files to any of their location so that screenshot can be viewed.
My code is below:
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String dest = "D:\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png";
File destination = new File("D:\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png");
FileUtils.copyFile(source, destination);
//FileUtils.copyFile(source, );
Instead of relative path. I found it is easier if the image is converted to base64 format. In that case, we only want to share .html file only.
TakesScreenshot ts = (TakesScreenshot)driver;
String dest = ts.getScreenshotAs(OutputType.BASE64);
return "data:image/jpg;base64, " + dest ;
I have used the extent report version 2.40.2 jar and have achieved sharing of my reports folder in this way. The paths are relative here and the report would render correctly with these paths. Hope this helps. I went through many links but nothing actually helped so came up with this logic.
public String capture() throws IOException {
try{
//take screenshot and save it in a file
File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//copy the file to the required path
File destinationFile = new File(System.getProperty("user.dir")+"/reports/image_" + System.currentTimeMillis()+ ".png");
FileHandler.copy(sourceFile, destinationFile);
String[] relatvePath = destinationFile.toString().split("reports");
screenshotPath = ".\\" + relatvePath[1];
}
catch(Exception e){
//if it fails to take screenshot then this block will execute
System.out.println("Failure to take screenshot "+e);
}
return screenshotPath;
}
test.log(LogStatus.FAIL, Constants.REPORT_ERROR, test.addScreenCapture(capture()) + Constants.REPORT_ERROR_STATUS);
Use relative path for your screenshots. Save your screenshots where your html file is located.
Use relative path for screenshot as below:
String path = System.getProperty("user.dir")+"\\ErrorScreenshots\\"+screenShotName+System.currentTimeMillis()+".png";
File destination = new File(path);

Handle download dialog box in SlimerJS

I have written a script that clicks on a link which can download a mp3 file. The problem I am facing is when the script simulates the click on that link, a download dialog box pops up like this:
Download Dialog Box
Now, I want to save this file to some path of my choice and automate this whole process. I am clueless on how to handle this dialog box.
Here's a script adapted from this blog post to download a file.
In SlimerJS it is possible to use response.body inside the onResourceReceived handler. However to prevent using too much memory it does not get anything by default. You have to first set page.captureContent to say what you want. You assign an array of regexes to page.captureContent to say which files to receive. The regex is applied to the mime-type. In the example code below I use /.*/ to mean "get everything". Using [/^image/.+$/] should just get images, etc.
var fs=require('fs');
var page = require('webpage').create();
fs.makeTree('contents');
page.captureContent = [ /.*/ ];
page.onResourceReceived = function(response) {
if(response.stage!="end" || !response.bodySize)
{
return;
}
var matches = response.url.match(/[/]([^/]+)$/);
var fname = "contents/"+matches[1];
console.log("Saving "+response.bodySize+" bytes to "+fname);
fs.write(fname,response.body);
phantom.exit();
};
page.onResourceRequested = function(requestData, networkRequest) {
//console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.open("http://....mp3", function(){
});
You can't control a dialog box. SlimerJS doesn't have API for this action.
Firefox generates a temp "downloadfile.extension.part" file which contains the content. Just simply rename the file ex. myfile.csv.part > myfile.csv
locally if working on a mac you should find the .part file in the downloads directory, on linux /temp/ folder
Not the most elegant solution but should do the trick