How to take a screenshot using python - selenium? - python

here is my simple code of python that I wrote to save the screenshot of a webpage.
from selenium import webdriver
import time
driver=webdriver.Firefox()
driver.get("https://www.google.co.in")
driver.implicitly_wait(2)
driver.save_screenshot("D\amanulla\test.png")
driver.quit()
Though, the program running without any errors, I do not see any screenshots saved on my machine. Can someone help me on this?

You are missing : from "D\amanulla\test.png" and you need to escape the \ as well, so effectively the line will be either:
"D:\\amanulla\\test.png"
or
"D:/amanulla/test.png"

I do not see any screenshots saved on my machine
Look for a file named Dmanulla est.png in the default Downloads location for your browser... because that is what you are instructing WebDriver to do with the line:
driver.save_screenshot("D\amanulla\test.png")
Explanation:
The string "D\amanulla\test.png" will be interpreted as "Dmanulla est.png". This is because backslashes are escape sequences within Python strings. Your directory separators will be interpreted as \a (bell) and \t (tab).
Also, the : separator is missing between the drive letter and the file path, so it is treating the entire string as a filename. In the absence of a directory name, it should save to browser's default "Downloads" directory.
Solution:
driver.save_screenshot(r"D:\amanulla\test.png")
This uses a raw string so the backslashes are not interpreted as escape sequences, and it adds the missing : as the drive letter separator.

Related

Can't replace character "\"

I've been working on a program that reads out an specific PDF and converts the data to an Excel file. The program itself already works, but while trying to refine some aspects I ran into a problem. What happens is the modules I'm working with read directories with simple slashes dividing each folder, such as:
"C:/Users/UserX"
While windows directories are divided by backslashes, such as:
"C:\Users\UserX"
I thought using a simple replace would work just fine:
directory.replace("\" ,"/")
But whenever I try to run the program, the \ isn't identified as a string. Instead it pops up as orange in the IDE I'm working with (PyCharm). Is there anyway to remediate this? Or maybe another useful solution?
In general you should work with the os.path package here.
os.getcwd() gives you the current directory, you can add a subfolder of it via more arguments, and put the filename last.
import os
path_to_file = os.path.join(os.getcwd(), "childFolder", filename)
In Python, the '\' character is represented by '\\':
directory.replace("\\" ,"/")
Just try adding another backslash.
First of all you need to pass "C:\Users\UserX" as a raw string. Use
directory=r"C:\Users\UserX"
Secondly, suppress the backslash using a second backslash.
directory.replace("\\" ,"/")
All of this is required as in python the backslash (\) is a special character known as an escape character.
Try this:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)
Output:<< C:/temp/myFolder/example/ >>

How do I write to a file with spaces and special characters in file name?

I'm trying to write to a file called
data/STO: INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv
using the following python code on windows
overwrite = "w" # or write new
f = open(OutputPath(copyNr), overwrite)
f.write(response.content.decode('utf-8'))
f.close()
print(f"Wrote to file: {OutputPath(copyNr)}")
The output in the console is correct, but the file written to results in only data/STO so the path seems to be clipped. I've tried to escape the characters using the method from this SO answer but that gave me an invalid_argument exception for the following filename:
data/STO\\:\\ INVE-B-TIME_SERIES_DAILY_ADJUSTED-1.csv
I get the same error when I remove the space and it still seems to clip at :. How do I include such characters in a filename?
You can't. Colons are only allowed on the volumeseperator - anywhere else there are illegal.
Allowed:
d:/somedir/somefile.txt
Illegal:
./some:dir/somefile.txt
and as seperators you can either use '\\' or '/' - both should be understood.
This is not a python limitation but a operating system limitation.
See f.e. What characters are forbidden in Windows and Linux directory names?
Windows API will not allow colon in filename, it is reserved for drive letter, use a different sign.

Jupyter Notebook encoding error?

I started to learn pandas by following this tutorial:
https://github.com/jvns/pandas-cookbook
Right in the first chapter I try very elementary example of reading a csv file. The example goes like this:
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")
I get a lengthy error message, which ends with a line:
FileNotFoundError: File b'..\\data\x08ikes.csv' does not exist
So although I write 'bikes.csv', which I have in the correct folder, the program seems to be searching for a file called 'x08ikes.csv'. Could this be an encoding error? sys.getdefaultencoding() returns 'utf-8'.
I am using Anaconda3 for 64bit Windows, version 4.4.0. My browser is Brave. Any ideas what is going wrong here?
The backslash character '\' has special meaning; it tries to "escape" the next character. In this case '\b' is an escape character that does have a meaning. There are three ways around this:
Escape the escapes:
You can use the backslash to escape the next backslash, telling Python "this is just another character"
broken_df = pd.read_csv("..\\data\\bikes.csv")
Use a raw string:
Placing r at the beginning of a string tells Python to interpret everything in the string as-is
broken_df = pd.read_csv(r"..\data\bikes.csv")
Use forward slashes:
This is specific to file paths. You can trace the directory to you file using forward slashes instead of backslashes.
broken_df = pd.read_csv("../data/bikes.csv")
What you can do is, upload the bikes.csv in to the Jupyter Home "Files" tab. Open it and you may still see the message. Then go to File->New, and you may get a new blank file. Open the original bikes.csv in notepad, copy and paste the content in to the file in jupyter notebook. This may help to resolve it.
Then you can run the following code.
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")

Trying to open folders ending with - in Python

I am trying to open png files with python. I just started but gets stuck when trying to access files in folders ending with - , the code works fine when I choose folders that don't end with - .
My idea was that - might be a special sign in Python somehow but I could not find any documentation for that. I am a beginner at Python so the answer might be obvious, you can see my code below.
import glob
import os
foldername='M:\mystuff\foldername-'
for pngfile in glob.glob(os.path.join(foldername, '*.png')):
print 'found'
Your backshashes aren't escaped, so your "\f" gets converted into an "\x0C" character.
You should escape the string
'M:\\mystuff\\foldername-'
or use a raw string
r'M:\mystuff\foldername-'

How to run a command line in Python

I am trying to execute
"C:/Program Files/AnsysEM/AnsysEM15.0/Win64/Designer.exe" -runscriptandexit "C:/Python27/simula_SIR_Phyton.py"
that is a to run a script in a program and I am not able to do it. I have succeed to run a single file like:
os.startfile("C:/Users/amrodri.UPVNET/Desktop/Scripts/SIR_europea_script.adsn")
But I have not succeed with the other problem. Can anyone help?
I have tried among others:
os.system("C:/Program Files/AnsysEM/AnsysEM15.0/Win64/Designer.exe" -runscriptandexit "C:/Python27/simula_SIR_Phyton.py")
os.system takes a single string as an argument. In order to have double quotes within a Python string (without terminating the string), you need to escape them using a backslash, like this:
os.system("\"C:/Program Files/AnsysEM/AnsysEM15.0/Win64/Designer.exe\" -runscriptandexit \"C:/Python27/simula_SIR_Phyton.py\"")
Or, alternatively, use single quotes instead:
os.system("'C:/Program Files/AnsysEM/AnsysEM15.0/Win64/Designer.exe' -runscriptandexit 'C:/Python27/simula_SIR_Phyton.py'")
See:
os.system()
Using quotes at the command line (This is Unix-specific, but should also apply to Windows if you're using something like PowerShell)
the culprit here is the space between Program and files. In windows, when you want to execute an address with an space in it, you need to put it between "", which is going to get mixed with Python's quotations. An easy solution would be to use raw '' in Python. For example:
import os
ansysedt_exe = r'"C:\Program Files\AnsysEM\AnsysEM16.0\Win64\ansysedt.exe" -runscriptandexit C:\automation\test_1.py'
print ansysedt_exe
os.system(ansysedt_exe)
Please notice that the designer address was put between "c:\...\designer.exe" because of the space in program files folder name, but we don't have to do the same for the script address, because there is no space there. Also just a heads up, in R16, designer.exe is going to be merged with AnsysEDT.exe.

Categories

Resources