I am using Selenium& Chrome Webdriver and I need to upload a Image file.
Since I cannot send the file using SendKeys, I am tring to handle the windows File Browser using PyWinAuto.
So after I click the find file button using selenium, I have to use PyWinAuto to find the windows file browser that has been opened, So I have used Applications().connect.
This is the code I need help with.
app=Application().connect(title_re="Open")
app.FileUpload.Edit.SetText("screenshot.png")
time.sleep(5)
app.FileUpload.Button.click()
The Error comes on the first row of the code, Which says
ElementNotFoundError: {'title_re': 'Open', 'backend': 'win32', 'visible_only': False}
I do not understand why the Element Cannot be found.
I upload a picture of the windows File browser I need to find.
The error that you are getting, looks like it's because it cannot find an application with the title of "Open". In your screenshot, it still looks like that's a Chrome window rather than a Window Explorer window.
The best way to know, is to use a tool to find different elements, a great one is 'inspect.exe' that comes standard on windows. Instructions on how to find this are here.
I've also found that sometimes, it's needed to use Desktop() rather than Application().
I suggest using uiautomation:
import uiautomation
path = uiautomation.EditControl(Name = "File name:")
path.SetFocus()
path.SendKeys(file_path)
btn = uiautomation.ButtonControl(Name = "Open")
btn.SetFocus()
btn.Invoke()
fil = uiautomation.EditControl(Name="File name:")
fil.SetFocus()
fil.SendKeys(file_name + '{Enter}')
You can use SendKeys(file_path + file_name + '{Enter}'), but in python the '\' is not dectected as a string, so I have to split them into 2 part.
With uiautomation, it works good for me, Here is the code
path = uiautomation.EditControl(Name = "File name:")
path.SetFocus()
path.SendKeys(file) #file=filepath
btn = uiautomation.ButtonControl(Name = "Open")
btn.SetFocus()
fil = uiautomation.EditControl(Name="File name:")
fil.SetFocus()
fil.SendKeys('{Enter}')
Instead of Application(), use Desktop() as shown below.
print_control_identifiers() will print identifiers for controls and its descendants. You can use appropriate control from the output to upload your file.
from pywinauto import Desktop
app=Desktop().window(title="Open")
app.print_control_identifiers()
Related
I try to download an image using requests module in python.It works but when i try to open this image it showing "Fatal error reading PNG image file: Not a PNG file". Here is my error screenshot.And the code i used to download is,
import requests
img_url = "http://dimik.pub/wp-content/uploads/2020/02/javaWeb.jpg"
r = requests.get(img_url)
with open("java_book.png","wb") as f:
f.write(r.content)
And i run my code in terminal just saying, python3 s.py (s.py is the name of file).
Is something wrong in my code or something else in my operating system(ubuntu 20.04 LTS)?
import requests
response = requests.get("https://devnote.in/wp-content/uploads/2020/04/devnote.png")
file = open("sample_image.png", "wb")
file.write(response.content)
print (response.content)
file.close()
https://devnote.in/wp-content/uploads/2020/04/devnote.png this url is Disable mod_security. so this return error like :
<html><head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>.
Disable mod_security using .htaccess on apache server
Mod_security can be easily disabled with the help of .htaccess.
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
It's because you tried to save javaWeb.jpg (A JPG file) as java_book.png (A PNG file).
In an attempt to see what we are working on, I've tried replicating the issue, please see below what found out.
1.) The file you are attempting to open is the ENTIRE HTML document. I can support this, because we are finding !DOCTYPE html at the beginning of your 'wb' or WRITE BINARY command.
<---------------------------------------------- WE ARE AT AN IMPASSE
From here we have a few options to solve our problem.
a.) We could simply download the image from the web page - placing it in a local folder/directory/ or wherever you want it. This is by far our easiest call, because it allows us to call and open it for later without having to do too much. While I'm on a Windows machine - Ubuntu should have no problem doing this either (Unless you aren't in an UBUNTU with a GUI - that can be fixed with startx IF SUPPORTED)
b.) If you have to pull directly from the site itself, you could try something like this using BEAUTIFULSOUP from this answer here. Honestly, I've never really used the latter option since downloading and moving is much more effective.
You just need to save the image as a JPG.
import requests
img_url = "http://dimik.pub/wp-content/uploads/2020/02/javaWeb.jpg"
r = requests.get(img_url)
with open("java_book.jpg","wb") as f:
f.write(r.content)
Yeah, it's a full HTML document:
TL;DR version - I need to programmatically add a password to .docx/.xlsx/.pptx files using LibreOffice and it doesn't work, and no errors are reported back either, my request to add a password is simply ignored, and a password-less version of the same file is saved.
In-depth:
I'm trying to script the ability to password-protect existing .docx/.xlsx/.pptx files using LibreOffice.
I'm using 64-bit LibreOffice 6.2.5.2 which is the latest version at the time of writing, on Windows 8.1 64-bit Professional.
Whilst I can do this manually via the UI - specifically, I open the "plain" document, do "Save As" and then tick "Save with Password", and enter the password in there, I cannot get this to work via any kind of automation. I'm been trying via Python/Uno, but to no gain. Although the code below correctly opens and saves the document, my attempt to add a password is completely ignored. Curiously, the file size shrinks from 12kb to 9kb when I do this.
Here is my code:
import socket
import uno
import sys
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
from com.sun.star.beans import PropertyValue
properties=[]
oDocB = desktop.loadComponentFromURL ("file:///C:/Docs/PlainDoc.docx","_blank",0, tuple(properties) )
sp=[]
sp1=PropertyValue()
sp1.Name='FilterName'
sp1.Value='MS Word 2007 XML'
sp.append(sp1)
sp2=PropertyValue()
sp2.Name='Password'
sp2.Value='secret'
sp.append(sp2)
oDocB.storeToURL("file:///C:/Docs/PasswordDoc.docx",sp)
oDocB.dispose()
I've had great results using Python/Uno to open password-protected files, but I cannot get it to protect a previously unprotected document. I've tried enabling the macro recorder and recording my actions - it recorded the following LibreOffice BASIC code:
sub SaveDoc
rem ----------------------------------------------------------------------
rem define variables
dim document as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------------------------------------------------------------------
dim args1(2) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = "file:///C:/Docs/PasswordDoc.docx"
args1(1).Name = "FilterName"
args1(1).Value = "MS Word 2007 XML"
args1(2).Name = "EncryptionData"
args1(2).Value = Array(Array("OOXPassword","secret"))
dispatcher.executeDispatch(document, ".uno:SaveAs", "", 0, args1())
end sub
Even when I try to run that, it...saves an unprotected document, with no password encryption. I've even tried converting the macro above into the equivalent Python code, but to no avail either. I don't get any errors, it simply doesn't protect the document.
Finally, out of desperation, I've even tried other approaches that don't include LibreOffice, for example, using the Apache POI library as per the following existing StackOverflow question:
Python or LibreOffice Save xlsx file encrypted with password
...but I just get an error saying "Error: Could not find or load main class org.python.util.jython". I've tried upgrading my JDK, tweaking the paths used in the example, i.e. had an "intelligent" go, but still no joy. I suspect the error above is trivial to fix, but I'm not a Java developer and lack the experience in this area.
Does anyone have any solution? Do you have some LibreOffice code that can do this (password-protect .docx/.xlsx/.pptx files)? Or OpenOffice for that matter, I'm not precious about which package I use. Or something else entirely!
NOTE: I appreciate this is trivial using full-fat Microsoft Office, but thanks to Microsoft's licensing restrictions, is a complete no-go for this project - I have to use an alternative.
The following example is from page 40 (file page 56) of Useful Macro Information
For OpenOffice.org by Andrew Pitonyak (http://www.pitonyak.org/AndrewMacro.odt). The document is directed to OpenOffice.org Basic but is generally applicable to LibreOffice as well. The example differs from the macro recorder version primarily in its use of the documented API rather than dispatch calls.
5.8.3. Save a document with a password
To save a document with a password, you must set the “Password”
attribute.
Listing 5.19: Save a document using a password.
Sub SaveDocumentWithPassword
Dim args(0) As New com.sun.star.beans.PropertyValue
Dim sURL$
args(0).Name ="Password"
args(0).Value = "test"
sURL=ConvertToURL("/andrew0/home/andy/test.odt")
ThisComponent.storeToURL(sURL, args())
End Sub
The argument name is case sensitive, so “password” will not work.
I found a tutorial and I'm trying to run this script, I did not work with python before.
tutorial
I've already seen what is running through logging.debug, checking whether it is connecting to google and trying to create csv file with other scripts
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from requests import get
import csv
def scrape_run():
with open('/Users/Work/Desktop/searches.txt') as searches:
for search in searches:
userQuery = search
raw = get("https://www.google.com/search?q=" + userQuery).text
page = fromstring(raw)
links = page.cssselect('.r a')
csvfile = '/Users/Work/Desktop/data.csv'
for row in links:
raw_url = row.get('href')
title = row.text_content()
if raw_url.startswith("/url?"):
url = parse_qs(urlparse(raw_url).query)['q']
csvRow = [userQuery, url[0], title]
with open(csvfile, 'a') as data:
writer = csv.writer(data)
writer.writerow(csvRow)
print(links)
scrape_run()
The TL;DR of this script is that it does three basic functions:
Locates and opens your searches.txt file.
Uses those keywords and searches the first page of Google for each
result.
Creates a new CSV file and prints the results (Keyword, URLs, and
page titles).
Solved
Google add captcha couse i use to many request
its work when i use mobile internet
Assuming the links variable is full and contains data - please verify.
if empty - test the api call itself you are making, maybe it returns something different than you expected.
Other than that - I think you just need to tweak a little bit your file handling.
https://www.guru99.com/reading-and-writing-files-in-python.html
here you can find some guidelines regarding file handling in python.
in my perspective, you need to make sure you create the file first.
start on with a script which is able to just create a file.
after that enhance the script to be able to write and append to the file.
from there on I think you are good to go and continue with you're script.
other than that I think that you would prefer opening the file only once instead of each loop, it could mean much faster execution time.
let me know if something is not clear.
I've been digging around this but no luck. So my question is: is not possible to open a new url in a new tab ? ( in this case using IE).
My scenario is, open IE, open website, log into it, do some tasks, then open a new tab with a new url in that tab. When I do that, the new url always open in the first tab, not in the new one. I looked for some solutions online but any worked and found many people with same issue. Code follows below:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
path_to_Ie = 'C:\\Python34\\IEDriver\\IEDriverServer.exe' # change path as needed
browser = webdriver.Ie(executable_path = path_to_Ie)
url = 'www.test1.com'
browser.get(url)
browser.find_element_by_xpath("//*[#id='username']").send_keys("user")
browser.find_element_by_xpath("//*[#id='password']").send_keys("pass")
browser.find_element_by_xpath("//*[#id='login-link']").click()
# some coding here
browser.find_element_by_tag_name("body").send_keys(Keys.CONTROL + 't') #open new tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) # it looks like it switches to the correct tab, but anyway the browser.get will open the url in the first tab
browser.get('www.test2.com') # this link must open in this new tab -> but it doesnt.
import os
os.system("taskkill /im IEDriverServer.exe")
thank you!
browser.execute_script("window.open('www.test2.com','_blank');")
This works for Chrome, but in IE it will open new window instead of new tab. If it doesn't matter for you then you can try it
I am trying to implement a simple application. It use wx.FileDialog to select a file, then display the file name in a wx.TextCtrl component.
It works allright at first, the file name was displayed as expected. However, when the mouse move over the text control component, the contents are gone.
Here is my code:
fdlg_input_dir = wx.FileDialog(dlg_input, "Choose input file", os.getcwd(), "", "All files(*.*)|*.*", wx.OPEN)
fdlg_input_dir.ShowModal()
textctrl_input_dir = wx.TextCtrl(dlg_input, 5, fdlg_input_dir.GetPath(), size=(300,20), pos=(85,20))
So my questions is, how to remain the contents in the TextCtrl component while the mouse moves over it?
Any suggestions are appreciated. Thanks.
Problem solved. It turns out that the initial text in the control component doesn't stand. Instead, using following code should archieve what I expected:
textctrl_input_dir.write(fdlg_input_dir.GetPath())