I wrote a pretty simple script to ping a website -> find an element by name -> check if it's displayed or not. The script seems to be working fine but throwing a weird error at the same time.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Chrome
driver = webdriver.Chrome(executable_path='D:/selenium_drivers/chromedriver.exe')
driver.get("http://newtours.demoaut.com/")
element = driver.find_element_by_name('userName')
print(element.is_displayed()) # T/F based on element's state
Here is the output from this script,
I get the output as True which is great, but it comes along with this error for reasons I can't quite comprehend at the moment.
[12080:16948:0505/181346.157:ERROR:browser_switcher_service.cc(238)] XXX Init()
Google Chrome Version: 81.0.4044.129 (64-bit)
Selenium Chromedriver Version: 81.0.4044.69
Operating System: Windows 10
I am not sure what the purpose of this call is; but it appears to be a harmless logging call. The relavant code is:
void BrowserSwitcherService::Init() {
LOG(ERROR) << "XXX Init()";
LoadRulesFromPrefs();
StartDownload(fetch_delay());
}
Which was added in this commit. Does this do anything? Or just print a message to the console? Are any Python errors raised?
I want a way to find the default browser in Python. I've seen https://docs.python.org/3.8/library/webbrowser.html
and there might be a way of converting a webbrowser instance which I do not know.
Does anybody know how I could go about doing that?
Also, I'm using Windows - it doesn't need to work for Mac or Ubuntu.
Edit:
I've already tried this website and it gives me an error saying that 'the file path does not exist'.
Additionally, I don't want to open a tab in the default browser, I just want the name.
Edit #2:
The following code works but returns Internet Explorer instead of my actual default which is Chrome.
from winreg import*
with OpenKey(HKEY_CLASSES_ROOT,r"http\\shell\\open\\command") as key:
cmd = QueryValue(key, None)
I have figured it out. I'm pretty sure this only works on Windows, but here's the code:
from winreg import *
with OpenKey(HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice") as key:
browser = QueryValueEx(key, 'Progid')[0]
It will return ChromeHTML for Chrome, FirefoxURL for Firefox, and IE.HTTP for Internet Explorer.
You can try this
import webbrowser
default_browser = webbrowser.get()
default_browser_name = default_browser.name
default_browser_basename = default_browser.basename
As the docs say
webbrowser.get([name])
Return a controller object for the browser type name. If name is empty, return a controller for a default browser appropriate to the caller’s environment.
How to upload a picture on a web application with the selenium testing tool? I am using python.
I tried many things, but nothing worked.
What I'm doing is this (make sure drv is an instance of webdriver):
drv.find_element_by_id("IdOfInputTypeFile").send_keys(os.getcwd()+"/image.png")
and then find your submit button and click it.
A very easy way to control components like windows file selector (or just your OS in general) is by using pyautogui. You can install pyautogui through pip
import pyautogui
... # set the webdriver etc.
...
...
element_present = EC.presence_of_element_located((By.XPATH, "//button[#title='Open file selector']")) # Example xpath
WebDriverWait(self.driver, 10).until(element_present).click() # This opens the windows file selector
pyautogui.write('C:/path_to_file')
pyautogui.press('enter')
I am using fine-uploader, running selenium tests with pytest and this worked for me:
elm = driver.find_element_by_xpath("//input[#type='file']")
elm.send_keys(os.getcwd() + "/tests/sample_files/Figure1.tif")
No form submission or Enter key is needed in my case.
I added an answer for anyone looking to use deal with the annoying msofiledialogs. This is working off of saravanan's proposed solution, but more fleshed out for Python.
I had a similar problem with a script I'm working on for a company on the side. I'm attempting to upload documents for a company's clients, but due to the way their site worked, I could not utilize send_keys to directly send the path, so I had to rely on msofiledialog.
You only need to install AutoIt
https://pypi.python.org/pypi/PyAutoIt/0.3 or just "pip install -U pyautoit" through the cmd screen
type "import autoit" on your script page
Type the following before the file dialog pops up in your script:
autoit.win_active("Open")
autoit.control_send("Open","Edit1",r"C:\Users\uu\Desktop\TestUpload.txt")
autoit.control_send("Open","Edit1","{ENTER}")
It will look for the open file dialog window and fill it out and press enter.
"Open" is the title of my file dialog screen. Put the title of yours in place of "Open". There are more creative ways to utilize AutoIt's functions, but this is an easy, straightforward way for beginners.
Edit: DO NOT. DO NOT use control_send on most things if you can avoid it. It has a well-known issue of sending erroneous text. In my case, the colon in my file path was being turned into a semi colon. If you need to send input keys, it should be fine, however if you need to send text, use control_set_text. It has the same syntax.
autoit.control_set_text("Open","Edit1",r"C:\Users\uu\Desktop\TestUpload.txt")
All these approach wont work with modern image uploaders in olx !!!
Alternative approach (only for windows )
1. Automation of windows can be done using Autoit
2. Install Autoit and SciTe Script editor
3. Autoit code :(imageupload.au3)
WinActivate("File Upload"); for chrome use "open" that is the name of the window that pops
send("D:\images\image1.png"); path of the file
Send("{ENTER}")
4. compile it to get an .exe file(imageupload.exe)
5. Now from python call the .exe file like
import os
import os.system('C:\images\imageupload.exe') #path of the .exe file
Upload input control opens a native dialog (it is done by browser) so clicking on the control or browse button via Selenium will just pop the dialog and the test will hang.
The workaround is to set the value of the upload input via JavaScript (in Java it is done via JavascriptExecutor) and then submit the form.
See this question for sample in C#, I am sure there's also a way to call JavaScript in Python but I never used Selenium Python bindings
Here is the code that i used:
Imagepath = "C:\User\Desktop\image.png"
driver.find_element_by_xpath('//html/body/input').send_keys(Imagepath)
driver.find_element_by_xpath('//html/body/button').click()
I accept the Answer by karloskar. Note It is not working for FireFox (59). And it is works with Chrome Driver only.
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Sendkeys("C:\text.txt")
shell.Sendkeys("~")
Will resolve the issue
You can easily add this one line of code to solve the problem:
driver.find_element_by_xpath("your fullpath").send_keys("C://1.png(your file root")
But pay attention, sometimes maybe you put a wrong xpath in first field. follow below steps for reach to rightful xpath:
open the inspect and click exactly on the box which you want to
upload the file.
right click on the html code and select xpath full address from copy
sub menu.
paste the root in xpath field in the code.
full code to achieve file upload using autoit tool.
u can just copy paste this and u can run, it will work since it is a acti-time demo.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import os
def fileUploading():
driver = webdriver.Firefox()
driver.implicitly_wait(20)
wait = WebDriverWait(driver, 10)
driver.get("https://demo.actitime.com/login.do");
driver.find_element(By.ID,"username").send_keys("admin")
driver.find_element(By.NAME, "pwd").send_keys("manager")
driver.find_element(By.XPATH, "//div[.='Login ']").click()
wait.until(ec.element_to_be_clickable((By.XPATH, "(//div[#class='popup_menu_icon'])[3]")))
driver.find_element(By.XPATH, "(//div[#class='popup_menu_icon'])[3]").click()
wait.until(ec.element_to_be_clickable((By.XPATH, "//a[contains(text(),'Contact actiTIME Support')]")))
driver.find_element(By.XPATH, "//a[contains(text(),'Contact actiTIME Support')]").click()
wait.until(ec.element_to_be_clickable((By.XPATH,"//div[#class='dz-default dz-message']")))
driver.find_element(By.XPATH,"//div[#class='dz-default dz-message']").click()
os.system("C:\\Users\\mallikar\\Desktop\\screenUpload.exe")
time.sleep(2000)
fileUploading()
below is the content of autoit code:
WinWaitActive("File Upload")
Send("D:\SoftwareTestingMaterial\UploadFile.txt")
Send("{ENTER}")
download autoIt and autoIt SCITE editor tool.
once done install autoit and the open the scite editor and paste the above code and save it with .au3 extension and once saved, right click on the file and select complile script(x64), now .exe file is created.
now use the below code:
os.system("C:\\Users\\mallikar\\Desktop\\screenUpload.exe")
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.example.org")
def upload_file():
upload_file = driver.find_element_by_id("paste here id of file which
is
enter code here`shown in html code...")
upload_file.send_keys("copy the path of file from your pc with name and
paste here...")
if toast message is disappeared within seconds you can use Chropath extension in chrome to find its xpath
This is a pure python code.
Instead of using control_send, use control_set_text to resolve inconsistencies present in the string sent to the window. See this link for reference: https://www.autoitscript.com/forum/topic/85929-incorrect-string-being-sent-via-controlsend/
import autoit
autoit.win_wait_active("Open")
autoit.control_set_text("Open", "Edit1", imgPath)
autoit.send("{ENTER}")
Use PyAutoGui if sendkeys function is not working on buttons.
sample code:
import pyautogui
driver.find_element_by_xpath("Enter Xpath of File upload button").click()
time.sleep(4) #waiting for window popup to open
pyautogui.write(r"C:\Users\AmarKumar\FilesForUploading\image.jpg") #path of File
pyautogui.press('enter')
I have used below script format to upload the images. This may help you.
Imagepath=os.path.abspath('.\\folder1\\subfolder2\file1.jpg')
driver.find_element_by_id("Id of the element").clear()
driver.find_element_by_id("Id of the element").send_keys(Imagepath)
if you do not have ID of the object ,then you can use xpath or css selector accordingly.
Using splinter :
browser.attach_file('file_chooser_id',fully_qualified_file_path)
If you are using service you will get an exception
service = Service('driver_path')
service.start()
driver = webdriver.Remote(service.service_url)
choose_image = driver.find_element(By.ID, 'id')
choose_image.send_keys(os.getcwd()+'/image.jpg')
Exception :
selenium.common.exceptions.WebDriverException: Message: unknown command: unknown command: session/$sessionId/se/file
Working code (suggestion - use id of the element instead of other)
driver=webdriver.Chrome(executable_path=driver_path)
choose_image=driver.find_element(By.ID, 'id')
choose_image.send_keys(os.path.join(os.getcwd(), 'image.jpg'))
In case you want to upload multiple pictures, you can alter the single image answer as follows:
images = ["/path/to/image1.png", "/path/to/image2.png","/path/to/image3.png"]
drv.find_element_by_id("IdOfInputTypeFile").send_keys("\n".join(images))
Note that the input form should have the multiple attribute set to True.
I post a solution that i consider best. it is a modification on solution by #sherlock (see my comment on that post)
import autoit
autoit.win_wait_active("Open")
autoit.control_set_text("Open", "Edit1", imgPath)
autoit.control_click("Open", "Button1")
Install these three
sudo apt-get install python3-tk python3-dev
pip install tk
pip install PyAutoGUI
use these two line of code.
pyautogui.write('/home/image.jpg')
pyautogui.press('enter')
I've tripped on a very easy to reproduce code that's driving me crazy.
I'm trying to take a picture of the screen after entering a container code in a website form, using Python and PhantomJS webdriver (selenium).
The code that makes it possible is quite short, and reproducing it in the console works fine. But if this same code is within a function or a script, it doesn't behave the same.
Here is the working code, that works for me writing it line by line in the console:
(Python version 2.7.9, selenium 2.53.6)
> python
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1280, 1024)
driver.get('http://www.track-trace.com/container')
driver.find_element_by_name('number').clear()
driver.find_element_by_name('number').send_keys('CGMU5109933')
driver.find_element_by_xpath('//input[#name="commit" and #value="Track direct"]').click()
driver.save_screenshot('./x.png')
However, this same code inside a function or a script only behaves the same until it reaches the click.
It freezes while loading, and the screenshot shows just that.
It doesn't matter what type of wait I try, implicit or explicit, the loading button won't end.
Here is the same code inside a function in foo.py module to make trying it easier.
The picture that is taken won't match the picture taken by the above code.
# foo.py
from selenium import webdriver
def try_it():
driver = webdriver.PhantomJS()
driver.set_window_size(1280, 1024)
driver.get('http://www.track-trace.com/container')
driver.find_element_by_name('number').clear()
driver.find_element_by_name('number').send_keys('CGMU5109933')
driver.find_element_by_xpath('//input[#name="commit" and #value="Track direct"]').click()
driver.save_screenshot('./x.png')
> python
>>> import foo
>>> foo.try_it()
The code must be in a function as it is called on demand when new search petitions arrive on a web service that is integrated in an application.
I always seek first for questions that may have valid answers but this time it doesn't seem to be anything similar to my problem.
Any idea why this may be happening and how to avoid it would be very much appreciated. If any other code or clarification is needed don't hesitate to ask.
This is purely a timing issue. Button clicks don't block, meaning once a click is issued, it returns and python runs the very next line right away. You need to wait until the next page has finished loading before you can take the screenshot. I would use an explicit wait that blocks until an element on the next page you're interested in has loaded. Likewise, I think you do need to worry about the popup asking if you really want to use direct.
My script:
from explicit import waiter
from selenium import webdriver
from selenium.webdriver.common.by import By
def locate_container(driver, container_id):
url = 'http://www.track-trace.com/container'
track_direct_xpath = '//input[#name="commit" and #value="Track direct"]'
im_sure_css = 'div.modal-footer button.jq-directinfo-continue'
tracking_details_header_css = 'div#wrapper > div.inner > h1'
# Load the container search page
driver.get(url)
# Locate the container field, enter container_id, click direct search button
waiter.find_write(driver, 'number', container_id, clear_first=True, by=By.NAME)
waiter.find_element(driver, track_direct_xpath, By.XPATH).click()
# Locate I'm Sure button and click it
waiter.find_element(driver, im_sure_css, By.CSS_SELECTOR).click()
# Wait for the "Tracking details for Container: XXX" header to load
waiter.find_element(driver, tracking_details_header_css, By.CSS_SELECTOR)
# Now we know the page has loaded and we can take the screenshot:
driver.save_screenshot('./x.png')
def main():
driver = webdriver.PhantomJS()
try:
driver.set_window_size(1280, 1024)
locate_container(driver, 'CGMU5109933')
finally:
driver.quit()
if __name__ == "__main__":
main()
(Full disclosure: I maintain the explicit package, which is meant to simplify using explicit waits. You can replace it with direct waits and get the same affect. Simply pip install explicit to install)
I want to use, on a webdriver Firefox instance, the "new tab instead of window" option.
1/ I created a profile with this option on, but when I use the profile a lot of options are OK but not this one.
2/ After the load of the profile I tried to change the option in the code but it does n't work.
My code :
profile = webdriver.FirefoxProfile(os.path.join(s_path, name))
profile.set_preference("browser.link.open_newwindow.restriction", 0)
profile.set_preference("browser.link.open_newwindow", 3)
profile.set_preference("browser.link.open_external", 3)
profile.set_preference("browser.startup.homepage","http://www.google.fr")
profile.update_preferences()
print(os.path.join(s_path, name))
driver = webdriver.Firefox(set_profile())
All is OK (the start homepage is google.fr) except this option which is not OK.
It seems that Selenium copy the profile in a temp dir. where users.js have the wrong line :
user_pref("browser.link.open_newwindow", 2);
Python 3.4.2, Windows 7, Firefox 39.0, Selenium lib 2.46
From what I've researched, browser.link.open_newwindow is a frozen setting and it's always synced with the value 2. If you dig up the source of the selenium Python bindings, you would find a set of frozen settings that is applied after your custom settings are set.
Note that in java bindings this set of default frozen settings is explicitly hardcoded:
/**
* Profile preferences that are essential to the FirefoxDriver operating correctly. Users are not
* permitted to override these values.
*/
private static final ImmutableMap<String, Object> FROZEN_PREFERENCES =
ImmutableMap.<String, Object>builder()
.put("app.update.auto", false)
.put("app.update.enabled", false)
.put("browser.download.manager.showWhenStarting", false)
.put("browser.EULA.override", true)
.put("browser.EULA.3.accepted", true)
.put("browser.link.open_external", 2)
.put("browser.link.open_newwindow", 2) // here it is
// ...
And a bit of an explanation coming from Firefox only supports windows not tabs:
This is a known issue and unfortunately we will not be supporting tabs.
We force Firefox to open all links in a new window. We can't access
the tabs to know when to switch. When we move to marionette (Mozilla
project) in the future we should be able to do this but for now it is
working as intended
A workaround solution would be to change the target of a link manually - may not work in all of the cases depending on how a new link is opened.
"browser.link.open_newwindow" is a frozen preference, which means that it can't be modified using profile.set_preference("browser.link.open_newwindow", 3)
The solution is to use profile.DEFAULT_PREFERENCES["frozen"]["browser.link.open_newwindow"] = 3 instead. (the other non-frozen preferences can be set with set_preference without problem)