Failed- Path too long error while downloading file in Chrome using selenium - selenium

I want to download file in my current working directory using selenium automation. But I am getting 'Path too long' error. The code I have written so far is:
os.chdir(os.path.dirname(__file__))
current_directory = os.getcwd()
windows_cwd = current_directory.replace('\\','\\\\')+'\\\\'
chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory': windows_cwd,
'download.directory_upgrade': True,
'safebrowsing.enabled': False,
'safebrowsing.disable_download_protection': True
}
chrome_options.add_experimental_option('prefs',prefs)
browser = webdriver.Chrome(options=chrome_options)
My current working directory is:
C:\Users\US177\PycharmProjects\Plugin
where the path is too long.
But it successfully downloads to
C:\Users\US177\Desktop
failed-long path

I'm not exactly sure what your question is based on the information provided, but I'm guessing it's along the lines of "Why is this happening?", so I will address that question.
The maximum length of a file name in Windows is 260 characters. The file is able to download to your desktop because the name of the file (when appended to your path) does not exceed this limit. When trying to download to PycharmProjects\Plugin\ folder, the path has become too long.

While setting your download path, try using double backslash (ie. path\\to\\directory).
See this Github issue about programatically downloading from chrome

Related

How to set default download path for chrome using selenium webdriver in ubuntu 20.04?

I am trying to save a zip file by using download as option inside a specific folder. I found a way by which I am able to download the file. But the problem where I am stuck is while setting default path in ubuntu it is taking frontslash /, whereas in windows it takes backslash \.
Below is my code which i am using to set the default path.
HashMap<String, Object> hashmap = new HashMap<>();
String defaultPath = System.getProperty("user.dir")+ "\\src\\main\\resources";
hashmap.put("download.default_directory", defaultPath);
options.setExperimentalOption("prefs", hashmap);
During execution the default path is set as below in Ubuntu 20.04 which causing the test case to fail as the file is downloaded in the default location.
/home/user/git/ui-automation\src\main\resources
Can someone help me to resolve this issue ?
You can use the Paths class to resolve file paths that are normalized to the underlying host system:
import java.nio.file.Paths
String userDir = System.getProperty("user.dir");
Strung defaultPath = Paths.get(userDir, "src", "main", "resources").toString();

Issue in taking screenshot in selenium while using chromedriver 73 for chrome version 73

When i tried to take screenshot of a webpage using selenium in python, i get error message selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 10.000.
Code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
indi_url = 'http://www.google.com'
options = Options()
options.add_argument("disable-infobars")
options.add_argument("--start-maximized")
options.add_argument("--disable-popup-blocking")
options.add_argument("disable-popup-blocking")
options.add_argument("--disable")
driver = webdriver.Chrome(options=options)
driver.get(indi_url)
driver.implicitly_wait(30)
driver.save_screenshot("new.png")
Error message:
I'm using Chrome version 73, chromedriver version 73.
Note: code was working fine (ie.screenshot)in lower version of chrome and chrome driver.
Help me out in fixing this issue for new version of chrome driver.
Thanks in advance
As the error shows, your filename for screenshot does not match the template extensions .png
Here is an example how to make a screenshot.
Java:
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(".\\Screenshots\\example_screenshot.png"));
Python:
driver.save_screenshot("screenshot.png")
This error message...
UserWarning: name used for saved screenshot does not match file type. It should end with a .png extension
"type. It should end with a .png extension", UserWarning)
...implies that the Selenium-Python client encountered an issue while invoking get_screenshot_as_file() method.
get_screenshot_as_file()
get_screenshot_as_file() saves a screenshot of the current window to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename.
Args:
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
Usage:
driver.get_screenshot_as_file('/Screenshots/foo.png')
Defination:
if not filename.lower().endswith('.png'):
warnings.warn("name used for saved screenshot does not match file "
"type. It should end with a `.png` extension", UserWarning)
png = self.get_screenshot_as_png()
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
return False
finally:
del png
return True
Analysis
As per the snapshot of the error stack trace:
You have used the command as:
driver.get_screenshot_as_file('new.jpeg')
The issues were:
The filename didn't end with .png
The desired full path of your filename wasn't provided.
Even if you desire to use save_screenshot() this method in-turn invokes get_screenshot_as_file(filename)
Solution
Create a directory within your project as Screenshots and provide the absolute path of the filename you desire for the screenshot while invoking either of the methods as follows:
driver.get_screenshot_as_file("./Screenshots/YakeshrajM.png")
driver.save_screenshot("./Screenshots/YakeshrajM.png")
Update
Currently GAed Chrome v73 have some issues and you may like to downgrade to Chrome v72. You can find a couple of relevant discussions in:
Getting Timed out receiving message from renderer: 600.000 When we execute selenium scripts using Jenkins windows service mode
Timed out receiving message from renderer: 10.000 while capturing screenshot using chromedriver and chrome through Jenkins on Windows

Cannot Download PDF's Using Selenium/Python 3.x, But It works When I do it Manually

I read through a ton of answers to this query of mine but couldn't find anything specific. Hence asking here
Here's the scenario, On a webpage, when I click a download button, it downloads a PDF file correctly, On the browser, I have set the Firefox preferences to save the file rather than open in preview.
However, when I run my selenium/Python script, the download keeps opening in the preview, there are other PDF downloads on the page and they work fine. Upon inspecting both the download buttons, the only difference I see is the one that does not download has a relative URL in its href value.
I am also using the following firefox options settings in my script, but with no help. Please guide me in the right direction. Thanks in advance!
**************************
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.download.dir", 'Path to Save The file')
fp.set_preference("pdfjs.enabledCache.state", False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")
fp.set_preference("pdfjs.disabled", "true")
# disable Adobe Acrobat PDF preview plugin
fp.set_preference("plugin.scan.plid.all", "false")
fp.set_preference("plugin.scan.Acrobat", "99.0")
self.driver = webdriver.Firefox(firefox_profile=fp,executable_path="path to my geckodriver")
self.driver.get("url")
I had the same problem - setting to disable pdfjs only worked when clicked manually on about:config page. Turned out that what seems to have solved the issue was (Firefox 60.6.1ESR):
profile.setPreference("pdfjs.disabled", true);
profile.setPreference("pdfjs.enabledCache.state", false); // <= THIS

Download word document in local folder using Rselenium

I am using R selenium to navigate through a website and eventually click a button that opens a dialog window to download the file. However, I want the file to automatically save in a different local folder.
My question is similar to this question.
Instead of using remDr <- remoteDriver(browserName = "firefox") I have tried
remDr <- remoteDriver(extraCapabilities = makeFirefoxProfile(list(
"browser.helperApps.neverAsk.saveToDisk"="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
)), but this gave an error that some local folder does not exist.
Note that I have no prior knowledge of Selenium and am quite new to programming.
All help welcome!
EDIT: because it it concerns a .docx file the correct MIME type appears to be: application/vnd.openxmlformats-officedocument.wordprocessingml.document. So I tried the following:
remDr <- remoteDriver(extraCapabilities = makeFirefoxProfile(list(
"browser.helperApps.neverAsk.saveToDisk"="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
))
but this gave following error:
Error in file(tmpfile, "rb") : cannot open the connection
In addition: Warning messages:
1: running command '"zip" -r9Xjq "C:\Users\PiKr\AppData\Local\Temp\RtmpApt5uQ\file19006f62c60.zip" "C:\Users\PiKr\AppData\Local\Temp\RtmpApt5uQ/firefoxprofile/prefs.js" ' had status 127
2: In file(tmpfile, "rb") :
cannot open file 'C:\Users\PiKr\AppData\Local\Temp\RtmpApt5uQ\file19006f62c60.zip': No such file or directory
I guess you must install the Rtools from the website and install the rtools before your proceed running the above program. Zipping action needs Rtools to perform. (Referring to the error 1)
Add the path to environment variable, if it doesn't add automatically

Program using selenium fails after building with cx_freeze

I'm developing an automatic web tester using Selenium (v2.37.2). Program works properly until I run the test built with cxfreeze (there is also tkinter gui).
there is the init function
def initDriver(self):
if self.browser == FIREFOX:
profile = webdriver.FirefoxProfile(profile_directory=self.profile);
self._driver = webdriver.Firefox(firefox_profile=profile)
elif self.browser == CHROME:
self._driver = webdriver.Chrome(self.executable, chrome_options=profile)
elif self.browser == IEXPLORER:
self._driver = webdriver.Ie(self.executable)
Now when I build it using Cx_freeze I get this error
method redirectToBlank(...) calls initDriver(..) as the first thingSo how I pack the .xpi file to the library.zip file - which option in setup.py I have to use? And do I even have to this?
And the second strange thing is, that the other browsers work fine, when I execute the .exe file in by clicking on its icon, but when I run it from command line, I get errors even for chrome and IE. (Sorry that the traceback isn't complete)
All paths are relative from the executed file (no matter from where you run it),
Thank you for any ideas to solve this problem.
(method redirectToBlank(...) calls initDriver(..) as the first thing)
First issue solved
It's problem with selenium - FirefoxProfile - class, which tries to load webdriver.xpi as a normal file, but selenium pack all libraries to a zip file, so selenium can't find it.
Even forcing cx_freeze in setup file to add webdriver.xpi to a proper directory in zip won't help.
It is necessary to edit FirefoxProfile (in firefox_profile module) class for example like this
def _install_extension(self, addon, unpack=True):
"""
Installs addon from a filepath, url
or directory of addons in the profile.
- path: url, path to .xpi, or directory of addons
- unpack: whether to unpack unless specified otherwise in the install.rdf
"""
if addon == WEBDRIVER_EXT:
# altered lines
import sdi.env
WEBDRIVER_SUBSTITUTE = "path/to/unpacked/webdrive.xpi"
addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_SUBSTITUTE)
# Original lines:
# addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
< the rest of the method >
Issue 2
OSError: win error 6: the handle is invalid problem wasn't caused by either cxfreeze or selenium. I run the final exe file from git bash. There's the problem. For some reason git bash doesn't open stdin for the program and that's why it fails. When I run it in standard windows command line, everything is ok or if i run it from git bash like program.exe < empty_file
what i did was remove selenium form packages list.
and put it inside includefiles, then it works.
like this :
includefiles = [(seleniumPackage,'')]
...
options = {'build_exe': {'includes':includes,
'excludes':excludes,
'optimize':2,
'packages':packages,
'include_files':includefiles,
...