Reputation: 412
Just met a strange problem while running selenium to take the screenshot of web page, below is part of my code:
url = "http://acme.com/licensemaker/licensemaker.cgi?state=California"
driver = webdriver.PhantomJS()
driver.maximize_window()
elem = driver.get(url)
elem = \
driver.find_element_by_xpath
('/html/body/form/center/div/table/tbody/tr[2]/td/input[2]')
elem.send_keys(comb)
driver.find_element_by_xpath
('/html/body/form/center/div/table/tbody/tr[2]/td/input[3]').click()
driver.save_screenshot('../screenshots/1.png')
print('ok')
img = driver.find_element_by_xpath('/html/body/center[1]/div/a/img')
location = img.location
size = img.size
print(size)
I try both PhantomJS and Safari driver neither can they save the screenshot, but I can get the output of both 'ok' and the value of 'location'. I don't understand why I can't save the screenshot.
Saving the file via absolute path failed but only name worked. I use the same version of Selenium last year it worked with relative path, what happened?
The result of save_screenshot()
is True
.
OS: macOS Sierra 10.12.5 Interpreter: 2.7.12(/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7) plus, I'm using Pyenv, and my Pyenv global is 'system'.
Upvotes: 0
Views: 3336
Reputation: 17593
You can use below function for relative path as absolute path is not a good idea to add in script
Import
import sys, os
Use code as below :
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")
make sure you create folder where .py file is present.
os.path.join also prevent you to run your script in cross platform like : unix and windows. It will generate path seprator as per OS in runtime. It is similer like File.separtor in java
Upvotes: 1
Reputation: 193338
You have to consider the fact that, while invoking save_screenshot()
you have to mention the full path you wish to save your screenshot to. This should end with a .png
extension. As per your case, you may consider to create a directory by the name "screenshots" within your project space through your IDE or manually. In your code mention the path as:
driver.save_screenshot('/screenshots/123.png')
Upvotes: 1