Saving a screenshot from selenium to absolute path - python

I'm currently trying to write a script (to plug in to a Django project) to take a screenshot of a full page of a website using Selenium.
Everything seems to be running OK - the path (fullimsavepath) builds OK (hence the print statement to output so I can see), selenium doesn't report any errors, and the script exits fine. However,
when I look for the actual screenshot in the path provided, it doesn't exist there. What am I doing wrong? Is it something to do with relative vs. absolute paths?
Running Python 3.8 on Windows inside pipenv.
Code:
import time
import os
from sitehawk.settings import BASE_DIR
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime, date
def takescreenshot(url='http://www.google.com', filename='testpng1'):
options = webdriver.ChromeOptions()
options.headless = True
# Need to replace executable path with environment variable or similar for production?
# At the moment it's an absolute path to the driver
driver = webdriver.Chrome(options=options,executable_path=r'C:/Users/gapbr/Documents/dev/sitehawk/sitehawk-project/screenshots/driver/chromedriver.exe')
driver.get(url)
# Set the path where the image should be saved
actualdate = datetime.now()
yr = actualdate.strftime('%Y')
mn = actualdate.strftime('%m')
filepng = filename+'.png'
fullimsavepath = os.path.join(BASE_DIR,'screenshots','captured-files',yr,mn,filepng)
print(fullimsavepath)
# Take the screenshot
S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height')) # May need manual adjustment
driver.find_element_by_tag_name('body').screenshot(fullimsavepath)
driver.quit()

Maybe Python have doubling of literals like Java does. Try to double your slashes in path like this:
driver = webdriver.Chrome(options=options,executable_path=r'C://Users/gapbr//Documents//dev//sitehawk//sitehawk-project//screenshots//driver//chromedriver.exe')

I have very little knowledge of python. But, for your reference, I have used the below code in my C# project to take a screenshot. I hope you get some ideas from this:
static public void getCapture(string No = "1")
{
//Screenshot
Screenshot ss = ((ITakesScreenshot)Tests.driver).GetScreenshot();
DateTime dt = DateTime.Now;
//Saving_the_screenshot_with_a_filename
var title = dt.ToString("yyyyMMddHHmm") + "_" + No + ".png";
string file = System.IO.Path.Combine(appSettings.Settings["ScreenShotPath"].Value);
if (string.IsNullOrEmpty(file))
{
file = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
ss.SaveAsFile(file + #"\" + title);
}

Related

python selenium datepicker gets cleared

I'm developing a python app that sets form componentes of a certain webpage (developed using vue3.js)
I'm able to set a datepicker's value, but, after that, next operation clears the dapicker away.
I must be doing something really fool, but I'm out of ideas.
Here's my code:
import sys
from selenium import webdriver
#-----------------------------------------------------------------------------------------------------------------------
driver_headfull = None
try:
driver_headfull = webdriver.Firefox()
firefox_options = webdriver.FirefoxOptions()
except Exception as e:
print('ERROR WHEN CREATING webdriver.Firefox()')
print("Please, verify you have installed: firefox and that geckodriver.exe's is in %PATH%")
print(e)
sys.exit(5)
#navigate to url
driver_headfull.get('http://a_certain_ip')
#set a datepicker
element_to_interact_with_headfull = driver_headfull.find_element_by_id('datesPolicyEffectiveDate')
driver_headfull.execute_script("arguments[0].value = '2020-07-01';", element_to_interact_with_headfull)
#set a <div> that behaves like a <select>.
element_to_interact_with_headfull = driver_headfull.find_element_by_id('industryDescription')
driver_headfull.execute_script("arguments[0].click();", element_to_interact_with_headfull)
element_pseudo_select_option_headfull = driver_headfull.find_element_by_id('descriptionIndustryoption0')
driver_headfull.execute_script("arguments[0].click();", element_pseudo_select_option_headfull)
# this very last instruction resets value of html_id=datesPolicyEffectiveDate (datepicker)
while(True):
pass
Any ideas will be so welcome!
Well, this was a pain. I'll post it in case it's of any use for someone.
It seems the component was reloaded, and I was setting the son of the component by means of
arguments[0].value = '2020-07-01';
so the parent wouldn't see the change, and would automatically reload the child with a default (empty) value.
Adding the following snippet solved my trouble:
driver_headfull.execute_script("arguments[0].value = '2021-07-01';", element_to_interact_with_headfull)
driver_headfull.execute_script("arguments[0].dispatchEvent(new Event('input', { bubbles: true }));", element_to_interact_with_headfull)

Python Selenium Firefox Custom Profiles Save

I just started learning selenium with python
from selenium import webdriver
MY_PROFILE = "D:\\FIREFOX_PROFILE"
FFP = webdriver.FirefoxProfile(MY_PROFILE)
print(FFP.profile_dir)
# OUTPUT: C:\Users\ABC\AppData\Local\Temp\****\***
# But it should be OUTPUT: D:\FIREFOX_PROFILE
DRIVER = webdriver.Firefox(firefox_profile = FFP)
print(FFP.profile_dir)
# OUTPUT: C:\Users\ABC\AppData\Local\Temp\****\***
# But it should be OUTPUT: D:\FIREFOX_PROFILE
I want to save my profile somewhere so that I can use it later on.
I also tried creating RUN -> firefox.exe -p and creating a new profile (I can't use the created profile). Nothing works.
I am using:
Selenium Version: 2.53.6
Python Version: 3.4.4
Firefox Version: Various(49.0.2, 45, 38 etc)
I searched in Google but I can't solve it. Is there any way to save the profile?
You need to take help of os module in python
import os
there you get functions (like .getcwd() ) to described in Files and Directories.
then use,
p = webdriver.FirefoxProfile()
p.set_preference('browser.download.folderList', 2 )
p.set_preference('browser.download.manager.showWhenStarting', false)
p.set_preference('browser.download.dir', os.getcwd())
p.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv/xls')
driver = webdriver.Firefox(p)
in short you can do so,
profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml")
possible duplicate of Setting selenium to use custom profile, but it keeps opening with default

Python 2.7 changing default browser for webbrower.open

I am trying to open a page a wrote and saved to a local server. Everything is great but it defaults to opening in IE instead of Chrome. Chrome is my default browser and couldn't find any helpful tips online.
Sample code:
import webbrowser
webbrowser.open('192.168.1.254:1337/SmartFormTest1.php')
Thanks in advance!
Alright, found the issue. My browser was correctly defaulted to chrome, the issue is the webbrowser.py file. Lines 539-563 read:
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except WindowsError:
# [Error 22] No application is associated with the specified
# file for this operation: '<URL>'
return False
else:
return True
_tryorder = []
_browsers = {}
# First try to use the default Windows browser
register("windows-default", WindowsDefault)
# Detect some common Windows browsers, fallback to IE
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
for browser in ("firefox", "firebird", "seamonkey", "mozilla",
"netscape", "opera", iexplore):
if _iscommand(browser):
register(browser, None, BackgroundBrowser(browse()
All I needed to do was add "chrome" to the list of for browser in (list).
Following the documentation, there are a few directions you can go with this:
Set the environment variable BROWSER
Use webbrowser.get('chrome') to get a controller instance of Chrome, then use that to do your browsing
Check your setup -- are you positive that your default browser is set properly? Does it appear under the "Internet" icon in your Start menu?
In Windows, the following code works for me.
chrome_path = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" %s'
webbrowser.get(chrome_path).open('google.com')
My browser was correctly defaulted to brave, just change it in the webbrowser.py file. Lines 539-563
In Line 540, just change the OS path to the desired browser you want to use. For Brave just change the path given to the iexplorer variable
like this:
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"BraveSoftware\\Brave-Browser\\Application\\brave.EXE")

How to load user CSS in a WebKit WebView using PyObjC?

I'd like to have a small browser that uses my own CSS.
The problem is that CSS is not loaded or, I guess, it loads but without any effect.
Here is the full code (I don't use an Interface Builder):
import Foundation
import WebKit
import AppKit
import objc
def main():
app = AppKit.NSApplication.sharedApplication()
rect = Foundation.NSMakeRect(100,350,600,800)
win = AppKit.NSWindow.alloc()
win.initWithContentRect_styleMask_backing_defer_(rect, AppKit.NSTitledWindowMask | AppKit.NSClosableWindowMask | AppKit.NSResizableWindowMask | AppKit.NSMiniaturizableWindowMask, AppKit.NSBackingStoreBuffered, False)
win.display()
win.orderFrontRegardless()
webview = WebKit.WebView.alloc()
webview.initWithFrame_(rect)
webview.preferences().setUserStyleSheetEnabled_(objc.YES)
print webview.preferences().userStyleSheetEnabled()
cssurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/user.css")
webview.preferences().setUserStyleSheetLocation_(cssurl)
print webview.preferences().userStyleSheetLocation()
pageurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/index.html")
req = Foundation.NSURLRequest.requestWithURL_(pageurl)
webview.mainFrame().loadRequest_(req)
win.setContentView_(webview)
app.run()
if __name__ == '__main__':
main()
The code runs without errors. Prints
True
http://dev.stanpol.ru/user.css
but there is no effect of my CSS in the WebView.
I tried different solutions like adding a link to the DOM:
pageurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/index.html")
req = Foundation.NSURLRequest.requestWithURL_(pageurl)
webview.mainFrame().loadRequest_(req)
dom = webview.mainFrame().DOMDocument()
link = dom.createElement_("link")
link.setAttribute_value_("rel", "StyleSheet")
link.setAttribute_value_("type", "text/css")
link.setAttribute_value_("href", "http://dev.stanpol.ru/user.css")
head = dom.getElementsByTagName_(u"head")
hf = head.item_(0)
hf.appendChild_(link)
but in either case it doesn't work.
I don't want to use javascript to load CSS.
Can anybody tell me what's wrong with setting user CSS in my code?
Apple doesn't properly document that setUserStyleSheetLocation can only be a local path or data: URL. Qt does explain this in their documentation of the corresponding setting in QtWebKit:
http://doc.qt.nokia.com/latest/qwebsettings.html#setUserStyleSheetUrl
Specifies the location of a user stylesheet to load with every web
page.
The location must be either a path on the local filesystem, or a
data URL with UTF-8 and Base64 encoded data, such as:
"data:text/css;charset=utf-8;base64,cCB7IGJhY2tncm91bmQtY29sb3I6IHJlZCB9Ow=="
Note: If the base64 data is not valid, the style will not be applied.

Flash-Selenium and Python

I want to try Flash-Selenium with the python driver, however I have some concerns regarding the available python extension, it seems aged and there is no example on how to use it... Is there anybody who is using it? Any example on how to use it ?
Example taken from FlashSelenium page:
from com.thoughtworks.selenium.FlashSelenium import FlashSelenium
from com.thoughtworks.selenium.selenium import selenium
url = "http://flashselenium.t35.com/colors.html"
browserType = "*firefox"
selenium = selenium("localhost", 4444, browserType, url)
selenium.start()
selenium.open(url)
flashApp = FlashSelenium(selenium, "coloredSquare")
flashApp.percent_loaded()

Categories