I am writing an script that will upload file from my local machine to an webpage. This is the url: https://tutorshelping.com/bulkask and there is a upload option. but i am trouble not getting how to upload it.
my current script:
import webbrowser, os
def fileUploader(dirname):
mydir = os.getcwd() + dirname
filelist = os.listdir(mydir)
for file in filelist:
filepath = mydir + file #This is the file absolte file path
print(filepath)
url = "https://tutorshelping.com/bulkask"
webbrowser.open_new(url) # open in default browser
webbrowser.get('firefox').open_new_tab(url)
if __name__ == '__main__':
dirname = '/testdir'
fileUploader(dirname)
A quick solution would be to use something like AppRobotic personal macro software to either interact with the Windows pop-ups and apps directly, or just use X,Y coordinates to move the mouse, click on buttons, and then to send keyboard keys to type or tab through your files.
Something like this would work when tweaked, so that it runs at the point when you're ready to click the upload button and browse for your file:
import win32com.client
x = win32com.client.Dispatch("AppRobotic.API")
import webbrowser
# specify URL
url = "https://www.google.com"
# open with default browser
webbrowser.open_new(url)
# wait a bit for page to open
x.Wait(3000)
# use UI Item Explorer to find the X,Y coordinates of Search box
x.MoveCursor(438, 435)
# click inside Search box
x.MouseLeftClick
x.Type("AppRobotic")
x.Type("{ENTER}")
I don't think the Python webbrowser package can do anything else than open a browser / tab with a specific url.
If I understand your question well, you want to open the page, set the file to upload and then simulate a button click. You can try pyppeteer for this.
Disclaimer: I have never used the Python version, only the JS version (puppeteer).
Related
This is the code immediately before I get stuck:
#Start a new post
driver.find_element_by_xpath("//span[normalize-space()='Start a post']").click()
time.sleep(2)
driver.find_element_by_xpath("//li-icon[#type='image-icon']//*[name()='svg']").click()
time.sleep(2)
The above code works well. The next step though has me puzzled.
I would like to upload the latest image file from my downloads folder. When I click on the link above in LinkedIn it navigates to my user folder (Melissa). (see image)
So... I'm looking for the next lines of code to navigate from the default folder to the Downloads folder (C:\Users\Melissa\Downloads), then, select the newest file, then click 'open' so it attaches to the LinkedIn post.
You can upload the image using this method:
import getpass, glob, os
# Replace this with the code to get the upload input tag
upload_button = driver.find_element_by_xpath("//input[#type='file']")
# Get downloads
downloads = glob.glob("C:\\Users\\{}\\Downloads\\*".format(getpass.getuser()))
# Find the latest downloaded file
latest_download = max(downloads, key=os.path.getctime)
# Enter it into the upload input tag
upload_button.send_keys(latest_download)
We have the function os.startfile() where I can pass the path to file so it would be opened in the default program if any one declared.
Now I need to open multiple files at once , using a simple for loop would open each one in a new instance or would close the previous files .
So is there a functions to which I can pass a list of paths to be opened at once?
For declaration : I need to emulate clicking on a file then pressing control then clicking on other file and finally pressing enter or using the open "open with" in file explorer.
edit: here is a photo of what i need to emulate from file explorer
edit: trying a simple for loop like this
import os
my_list = [ "D:\Music\Videoder\Abyusif I أبيوسف\ِAbyusif - Kol 7aga Bteb2a Gham2a l أبيوسف - كل حاجة بتبقى غامقة.mp3",
"D:\Music\Videoder\Abyusif I أبيوسف\Abyusif- 3ala maydoub eltalg (Prod by NGM) l أبيوسف- على ما يدوب التلج.mp3"]
for song in my_list:
os.startfile(song)
this would open the last element in the list , as after opening each file the previous is closed
If I understood your question correctly, you could use a simple for loop.
Code:
import os
file_paths = ["<file path here>", "<file path here>"]
for file in file_paths:
os.startfile(file)
Well, if you only want to execute music files, a quick and dirty way can be achieved like so:
import os
import time
from win32com.client import Dispatch
my_song_list = [
r'path\to\my\awesome\music\1.mp3',
r'path\to\my\awesome\music\2.mp3',
r'path\to\my\awesome\music\3.mp3'
]
wmp = Dispatch('WMPlayer.OCX')
for i, path in enumerate(my_song_list):
song = wmp.newMedia(path)
os.startfile(path)
if i < len(my_song_list) - 1:
time.sleep(song.duration)
Using the Windows Media Player to get the song's duration, then, running the audio file (openig with default player), and waiting exactly the duration to run the next.
I have a truckload of trace files I'm trying to catalog. The idea is to open each one with "chrome://tracing" then save a screenshot. Screenshots are easy to catalog.
Here is the process:
start chrome = works
open "chrome://tracing" = works
open file <== missing part <- I need help with
save screenshot = works
There are 2 ways to open the file in chrome://tracing:
a) - use the "load" button, navigate to file and open
Update: I was able to locate and click on the "Load" button using Selenium
Now - need to handle the file open / loading ??
b) - drag and drop a trace file to the main part of the window - opens it
[ no idea how to do this..]
Here is the actual code I have so far:
from selenium import webdriver
driver = webdriver.Chrome() # Optional argument, if not specified will search path
driver.get("chrome://tracing");
time.sleep(2) # Let the user actually see something
# Find load button
# or drop file to main window ?
# Send the file location to the button
file_location = 'C:\........json'
driver.send_keys(file_location) # don't know where to sent it :: idea from https://towardsdatascience.com/controlling-the-web-with-python-6fceb22c5f08
time.sleep(15) # some files are big - might take 15 seconds to load
date_stamp = str(datetime.datetime.now()).split('.')[0]
date_stamp = date_stamp.replace(" ", "_").replace(":", "_").replace("-", "_")
file_name = date_stamp + ".png"
driver.save_screenshot(file_name)
After some research and trial and error here is my final(?) working code
located "Load" button and opened the file Open dialog
used pywinauto to take care communication with the Open dialog
saved a screenshot - using a unique filename generated from datestamp
import time
from selenium import webdriver
from pywinauto.application import Application
import datetime
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(chrome_options=options)
driver.get("chrome://tracing");
time.sleep(2)
# Find load button
sdomele = driver.find_element_by_tag_name("tr-ui-timeline-view")
ele = driver.execute_script("return arguments[0].shadowRoot;",sdomele)
button_found = ele.find_element_by_id("load-button")
button_found.click() # let's load that file
time.sleep(3)
# here comes the pywinauto part to take care communication with the Open file dialog
app = Application().connect(title='Open') # connect to an existing window
dlg = app.window(title='Open') # communicate with this window
#file_location = os.path.join(submission_dir, folder, file_name)
file_location = "C:\\FILES2OPEN\\file01.json"
app.dlg.type_keys(file_location) # txt goes to the "File Name" box
time.sleep(2) #type is slow - this is just for safety
app.dlg.OpenButton.click() # click the open button
time.sleep(15) # some files might be big
# generate filename based on current time
date_stamp = str(datetime.datetime.now()).split('.')[0]
date_stamp = date_stamp.replace(" ", "_").replace(":", "_").replace("-", "_")
file_name = date_stamp + ".png"
driver.save_screenshot(file_name) # save screenshot (just the "inner" part of the browser window / not a full screenshot)
time.sleep(2)
driver.quit()
The reason you were not able to find the load button is because its present in a shadow dom. So first you need to find the shadow dom using execute_script ,then locate the "load" button as usual. The following code worked for me :
sdomele = _driver.find_element_by_tag_name("tr-ui-timeline-view")
ele = _driver.execute_script("return arguments[0].shadowRoot;",sdomele)
ele.find_element_by_id("load-button").click()
I'm a python beginner and I want my code to open a local HTML page with parameters (e.g. /help/index.html#1). Right now I have the below code:
def openHelp(self, helpid):
import subprocess
import webbrowser
import sys, os
directory = os.getcwd()
if sys.platform == 'darwin': # For macOS
url = 'file://' + directory + '/help/index.html' + '#{}'.format(str(helpid))
webbrowser.get().open(url)
else:
url = 'help/index.html' + '#{}'.format(str(helpid))
webbrowser.open(url)
The code opens the webpage, however without the parameters (#helpid). Where did I make a mistake? Thanks in advance!
Your code looked fine to me. I tried it and it worked. You have to call it with openHelp("",1). The #helpid parameter was added correctly. Make sure it is a number.
I have a list of links, which is stored in a file. I would like to open all the links in my browsers via some script instead of manually copy-pasting every items.
For example, OS: MAC OS X; Browser: Chrome; Script: Python (prefered)
Take a look at the webbrowser module.
import webbrowser
urls = ['http://www.google.com', 'http://www.reddit.com', 'http://stackoverflow.com']
b = webbrowser.get('firefox')
for url in urls:
b.open(url)
P.S.: support for Chrome has been included in the version 3.3, but Python 3.3 is still a release candidate.
Since you're on a mac, you can just use the subprocess module to call open http://link1 http://link2 http://link3. For example:
from subprocess import call
call(["open","http://www.google.com", "http://www.stackoverflow.com"])
Note that this will just open your default browser; however, you could simply replace the open command with the specific browser's command to choose your browser.
Here's a full example for files of the general format
alink
http://anotherlink
(etc.)
from subprocess import call
import re
import sys
links = []
filename = 'test'
try:
with open(filename) as linkListFile:
for line in linkListFile:
link = line.strip()
if link != '':
if re.match('http://.+|https://.+|ftp://.+|file://.+',link.lower()):
links.append(link)
else:
links.append('http://' + link)
except IOError:
print 'Failed to open the file "%s".\nExiting.'
sys.exit()
print links
call(["open"]+links)