Uploading Image with requests/selenium/pywinauto - python

Am trying to automate some postings on a couple different websites. Basically fill out my form and upload them to 3 sites with Selenium or requests. The image upload on this site opens a new window and asks you to specify the file path, or you can drag and drop the files. Here is what is looks like.
And without CSS here is what it looks like.
I abandoned requests earlier thinking there was no way I was going to be able to do anything with it. Moved to selenium and can click on the button and open the window but cannot actually place an image to upload in there. I have tried pywinauto and keep getting ElementNotVisible. I am having a hard time looking through the docs to find what to actually do. Where to go from here?

Try the below.
eleBrowse = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, '//input[#type='file']')))
# replace the path below with the one which you want to upload. If you want to send multiple files use comma as separator.
eleBrowse.send_keys("path")

Related

How to automate uploading photos to a website?

For the website 'https://web-en.wallapop.com/catalog/upload', if one tries to upload an add and scrolls down, photos can also be uploaded. How would I automate the uploading of a photo to this website with python?
I am currently writing a program that automatically creates adds on this website, however I do not know how to automate the uploading of a photo, located in my repository, to the website. I need to interact with the file explorer to pick the image and I do not know how to automate that. I do not even know if that is the right approach.
Any help is greatly appreciated!
driver.find_element_by_xpath('/html/body/tsl-root/tsl-upload/div/div/tsl-upload-product/form/div[2]/tsl-drop-area/div/div[2]/div/div[2]/label/input').send_keys(r'C:\Users\Nicolas Sanchez\3D Objects\Freelancer\Alberto\imagenes\i1473749533.jpg')
This works. This was my first thought initially however I was picking the wrong xpath selectors. This is the right xpath selector.

How to save a webpage by setting preferences in python for webdriver?

I am currently trying to save a webpage as it appears on the website in html format. Approach I am using is prerssing Ctrl + S using autoit. On pressing that save as dialog box appears where I am asked to enter the name of the file to save. This is working fine. However, I want to save the file by pressing Ctrl + S instead of bring the dialog box in front. I read somewhere by using "set_preference" we can do that. CAn someone suggest how to set a preference. Below is the code I am using for Chrome broswer:
driver=Webdriver.Chrome()
driver.get('http://www.yahoo.com/')
autoit.send("{CTRL down}")
autoit.send("{CTRL down}")
autoit.send("{CTRL up}")
autoit.send("C:\\Users\\karanjuneja\\Downloads\\kj\\ABCD.mhtml")
autoit.send("{ENTER}")
Currently I am using the aboved code, however I want that on pressing Ctrl + S it saves the file in the desired location.
Thanks
Karan
Selenium isn't the designed for this, you could either:
Use getHtmlSource and parse the resulting HTML for references to external files, which you can then download and store outside of Selenium.
Use something other than Selenium to download and store an offline version of a website - I'm sure there are plenty of tools that could do this if you do a search. For example WGet can perform a recursive download (http://en.wikipedia.org/wiki/Wget#Recursive_download)
Is there any reason you want to use Selenium? Is this part of your testing strategy or are you just wanting to find a tool that will create an offline copy of a page?

Interacting with pop-up boxes using selenium in python

I'm trying to use the Selenium module in python to generate a text list from one website, save it in a directory, and browse to that text list on another site to submit it.
I'm working on the script in two parts- 1. Get metadata and 2. Order data. I've successfully completed the script in part 1, except for the very last thing: Choosing to save the metadata file that was just generated. I left it alone to work on part 2, hoping I would stumble upon the answer, but I'm just reaching to same problem when the pop-up to choose file comes along.
In the documentation, I'm told that Selenium WebDriver has built-in support for handling popup dialog boxes and that after triggering a dialog box, if I call alert = driver.switch_to_alert() then I can "accept, dismiss, read its contents, or even type into a prompt."
However, it's not working. When I try alert.text('some text') or alert.send_keys(Keys.TAB), I keep getting the error NoAlertPresentException: Message: No alert is present and after adding the command to wait, I get the error TimeoutException: Message:
Are the popups I'm getting (screenshots attached) not recognized by Selenium? If so, how do I interact with them? It seems like using this to save and/or upload files is something that many people have to do, but I cannot find anything on Google. Specifically, I would like to choose 'Save File' then 'OK' for the first image and for the second I would like to browse to the file (i.e. enter the path into the file name field) and click 'Open.' I don't want to just change my Firefox settings to automatically save because this will eventually be run in a different environment, and that won't help solve my second problem.
Thanks!
EDIT:
I'm testing my script on windows but it will eventually be implemented on a linux cloud server. I thought I was going to have to switch to PhantomJS webdriver (which was probably going to make my problem worse) to do headless browsing but I found a way to keep firefox. I guess all this means is that I can't use AutoIT to fix my problem.
The popups you see are not regular popups that can be interacted with using switch_to. These popups are system dialogs and cannot be automated using selenium.
Usually people avoid having these dialogs shown in the first place by tweaking browser preferences, e.g.:
downloading file using selenium
Access to file download dialog in Firefox
How to download a file using Selenium's WebDriver?
For uploading, usually you can find the appropriate input element and send keys to it with a path to the file:
How to upload file ( picture ) with selenium, python
How to upload files into file inputs? (python-selenium docs)
Let me know if your case cannot be solved by using the answers in the links I've attached.
As for your first, "download file automatically" problem, you just need to set a correct content-type:
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "application/xml,text/xml")
Second problem fix (upload part):
driver.find_element_by_name("input_product_list").send_keys(textpath)
driver.find_element_by_name('include_sr').click()
driver.find_element_by_id('submit').click()
Extremely simple implementation using AutoIT.
Below scripts and steps can hely you to click on 'Save>OK' on this window's pop-UP
Step 1: Download AutoIT package/tool here AutoIt You may select ZIP format (extract it)
Step 2: Open any text editor (say notepad) and copy below code and save with extension .au3
(e.g file.au3)
WinWait("[TITLE:Opening ; CLASS:MozillaDialogClass]","", 10)
If WinExists("[TITLE:Opening ; CLASS:MozillaDialogClass]") Then
WinActivate("[TITLE:Opening ; CLASS:MozillaDialogClass]")
Send("{DOWN}")
Sleep(20)
Send("{TAB}")
Sleep(20)
Send("{TAB}")
Sleep(20)
Send("{ENTER}")
EndIf
Step 3: From extracted zip (Step 1) look for folder named: Aut2Exe and open it
Step 4: Click Aut2exe_x64.exe if your OS is 64 bit otherwise click Aut2exe.exe
Step 5: Browse/Locate file created in Step2. (file saved as extension .a3)
AND Choose Destination (.exe/.a3x) and select .exe option (say file.exe)
AND then Click convert
Step 6: include this file.exe in your project folder and use it as per your requirement using below code (as it is in Eclipse):
driver.dwonload().click(); // it can be something else as per your flow
Runtime.getRuntime().exec("C:/*path_to_your_EXE_file(selected in step 6))*/file.exe");

Uploading a file into a popup window with selenium

I have searched the forums and found some information regarding this, but not quite with the problem I'm facing. I am automating the uploading of files to a website. Unfortunately, the website uses a counter for the id of the "browse" button. Using Selenium and Firebug, I was able to find another way to identify the button. I have exported the script into python to add variables so I can automate. However, the browse button opens a windows popup to select the file. The script is started out like this...
driver.find_element_by_xpath("//*[#type=\"file\"]").click()
driver.find_element_by_id("upfile_1405369589849").clear()
driver.find_element_by_id("upfile_1405369589849").send_keys("path\\file")
driver.find_element_by_id("upload_button").click()
In this, the upload button is clicked, the popup appears, and it sits there mocking me. I tried using the xpath in place of the id, but that didn't work. I tried the following, too...
driver.findElement(By.id()).send_keys("path\\file")
and tried this...
driver.find_element_by_id("upfile_*").send_keys("path\\file")
I cant seem to get the window to respond, other than it's mocking glare. Any help to squelch this would be very appreciated.
It can´t be done. One workaround is to get the development team to modify the AUT for you. Add a javascipt function into the page that will allow you to pass the filename to the handler without having to click the browse button.
If you can´t do that, I would suggest that you look into Sikuli that will allow you to interact with the windows prompt using pattern recognition (screenshots) of what you want to interact with.

Can I Use Python to Make a Delete Button in a 'web page'

I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list.
I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory.
Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.
You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a "Keep this page" and a "Delete this page." When you click either button, the main page refreshes, this time with the next autocreated page in the frame.
You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a "delete".
You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file.
Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py.
You would start your script and point a browser at http://localhost:8080, for instance. The web browser would be your user interface.
To achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion.
Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience
def OnDelete(self, event):
assert self.current, "invalid delete operation"
try:
os.remove(os.path.join(self.cwd, self.current))

Categories

Resources