Selenium send_keys ignores space - python

I'm trying to write a name into an input field, but it seems to ignore the space between the first and last name, which is quite important in this instance. Have anybody else experienced similar problems? I'm running the script locally on a Firefox browser (33.1.1) on a Mac.
My code:
#write given message to element specified by name
def write_to_input(self,name,message):
inputEl = self.driver.find_element_by_name(name)
inputEl.send_keys(message)
#writing name
self.write_to_input("name","John Doe")

Related

Running find_all() commands in a new view via Sublime Text Plugin changes it into an Instant File Search

I am building an internal plugin for Sublime Text 3 to automate some changes we need done in our HTML.
I'm close to finishing it so we can start using it but I just have one small issue I can't seem to find a solution for.
The plugin will search for some specific HTML code, save them in a file and then modify the code in the view to reference some text in a json file. Then the plugin will open a new view and paste the contents of the file we saved some code in step 1. After which, I need to do some formatting in the new view (replace commas, quotes and brackets with a new line) and then run another internal sublime command in the new view.
The issue is after replacing the commas, quotes and brackets with a new line, the new view changes to an "Instant File Search" which messes with how the view runs the next command and inserts some garbage characters.
Example of the code:
#Open new tab and paste the copied subheads
newView = self.view.window().new_file(syntax="HTML.sublime-syntax")
newView.insert(edit, 0, json.dumps(sections))
# Clear any current selections in the new view
newView.sel().clear()
# Remove quotes, commas and square brackets and separate into new lines
q = newView.find_all(r"(\x{0022}\,\s\x{0022})|(\[\x{0022})|(\x{0022}\])")
for region in reversed(q):
newView.sel().add(region)
newView.replace(edit, region, "\n")
# Clear any current selections in the new view
newView.sel().clear()
q = newView.find_all("{% r")
for region in reversed(q):
newView.sel().add(region)
newView.replace(edit, region, "<p>{% r")
# Clear any current selections in the new view
newView.sel().clear()
q = newView.find_all("endreplace %}")
for region in reversed(q):
newView.sel().add(region)
newView.replace(edit, region, "endreplace %}</p>")
This is what it outputs in the new view:
If I click undo, I get the expected output which seems to mean sublime does something extra after running the last find_all code.
I haven't found anything online regarding this issue so I'm unable to try things to fix this.
Does anyone have an idea on how I should proceed?
P.S. One possible solution is to manually open a new view and run some commands but I'm trying to do all of that in 1 step using my plugin.

How to get LibreOffice headless Calc calculate to save new values from uno?

I am trying to open an excel file from python, get it to recalculate and then save it with the newly calculated values.
The spreadsheet is large and opens fine in LibreOffice with GUI, and initially shows old values. If I then do a Data->Calculate->Recalculate Hard I see the correct values, and I can of course saveas and all seems fine.
But, there are multiple large spreadsheets I want to do it from so I don't want to use a GUI instead I want to use Python. The following all seems to work to create a new spreadsheet but it doesn't have the new values (unless I again manually do a recalculate hard)
I'm running on Linux. First I do this:
soffice --headless --nologo --nofirststartwizard --accept="socket,host=0.0.0.0,port=8100,tcpNoDelay=1;urp"
Then, here is sample python code:
import uno
local = uno.getComponentContext()
resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
context = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager")
remoteContext = context.getPropertyValue("DefaultContext")
desktop = context.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext)
document = desktop.getCurrentComponent()
file_url="file://foo.xlsx"
document = desktop.loadComponentFromURL(file_url, "_blank", 0, ())
controller=document.getCurrentController()
sheet=document.getSheets().getByIndex(0)
controller.setActiveSheet(sheet)
document.calculateAll()
file__out_url="file://foo_out.xlsx"
from com.sun.star.beans import PropertyValue
pv_filtername = PropertyValue()
pv_filtername.Name = "FilterName"
pv_filtername.Value = "Calc MS Excel 2007 XML"
document.storeAsURL(file__out_url, (pv_filtername,))
document.dispose()
After running the above code, and opening foo_out.xlsx it shows the "old" values, not the recalculated values. I know that the calculateAll() is taking a little while, as I would expect for it to do the recalculation. But, the new values don't seem to actually get saved.
If I open it in Excel it does an auto-recalculate and shows the correct values and if I open in LibreOffice and do Recalculate Hard it shows the correct values. But, what I need is to save it, from python like above, so that it already contains the recalculated values.
Is there any way to do that?
Essentially, what I want to do from python is:
open, recalculate hard, saveas
It seems that this was a problem with an older version of LibreOffice. I was using 5.0.6.2, on Linux, and even though I was recalculating, the new values were not even showing up when I extracted the cell values directly.
However, I upgraded to 6.2 and the problem has gone away, using the same code and the same input files.
I decided to just answer my own question, instead of deleting it, as this was leading to a frustration until I solved it.

Python KeyError if logic or try logic

I'm trying to loop through some JSON data to export to CSV and all is going well until I get to a portion of the data that I need to get certain field values where these fields do not always exist beneath "tags".
I'm getting the error of:
for alarm in tag["alarmst"]:
KeyError: 'alarmst'
I believe from Built-in Exceptions reading that this means the key/field just does not exist.
I read in Errors and Exceptions that I can put this logic in a try statement to say, if this key does not exist, don't give me the error and do something else or move onto the next set of records beneath "tag" where "alarmst" is and just dump that (and the other fields specified) to the file.
I'm having trouble figuring out how to tell this logic to stop giving me this error and to only use the csv_file.writerow() function with all the field values if only the "alarmst" exist.
Since I will be working with one file and processes before this Python process runs will get the "devs" and the "tags" to their own CSV files, I cannot parse the data and cut down on the for loops within the other for loops.
I'm not sure if the issue with the if tag["alarmst"] in tag: is due to there being so many for loops within others, or if I need to use a try statement somehow instead, or if I'm just not doing something else correctly since I'm new to Python at this level of coding but it seems to work for the need thus far.
I'm running this on Windows 10 OS if that makes any difference but I assume it doesn't.
Starting Code:
import json
import csv
with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
data = json.load(file)
with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
csv_file = csv.writer(file)
for dev in data["devs"]:
for tag in dev["tags"]:
for alarm in tag["alarmst"]:
csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
If Code:
import json
import csv
with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
data = json.load(file)
with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
csv_file = csv.writer(file)
for dev in data["devs"]:
for tag in dev["tags"]:
for alarm in tag["alarmst"]:
if tag["alarmst"] in tag:
csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
tag["alarmst"] is what throws the error. It means getting the value from tag associated with the key "alarmst" and there is no such key so it fails. if tag["alarmst"] in tag will throw the same error, and moreover you won't even reach that point if it's below for alarm in tag["alarmst"]:. What you want is:
if "alarmst" in tag:
for alarm in tag["alarmst"]:
But much nicer is:
for alarm in tag.get("alarmst", []):
get is similar to usual square bracket access but the second argument is a default if the key is not found. So if "alarmst" is not in the dictionary this will essentially be:
for alarm in []:
which is just an empty loop that won't run at all.

Open URL stored in a csv file

I'm almost an absolute beginner in Python, but I am asked to manage some difficult task. I have read many tutorials and found some very useful tips on this website, but I think that this question was not asked until now, or at least in the way I tried it in the search engine.
I have managed to write some url in a csv file. Now I would like to write a script able to open this file, to open the urls, and write their content in a dictionary. But I have failed : my script can print these addresses, but cannot process the file.
Interestingly, my script dit not send the same error message each time. Here the last : req.timeout = timeout
AttributeError: 'list' object has no attribute 'timeout'
So I think my script faces several problems :
1- is my method to open url the right one ?
2 - and what is wrong in the way I build the dictionnary ?
Here is my attempt below. Thanks in advance to those who would help me !
import csv
import urllib
dict = {}
test = csv.reader(open("read.csv","rb"))
for z in test:
sock = urllib.urlopen(z)
source = sock.read()
dict[z] = source
sock.close()
print dict
First thing, don't shadow built-ins. Rename your dictionary to something else as dict is used to create new dictionaries.
Secondly, the csv reader creates a list per line that would contain all the columns. Either reference the column explicitly by urllib.urlopen(z[0]) # First column in the line or open the file with a normal open() and iterate through it.
Apart from that, it works for me.

Send a file between 2 mobile phones via bluetooth using Python

I am trying to send a file between two mobile phones using Python language
for the phone that will send i used this code:
import socket,e32socket,appuifw
socket=e32socket.socket(e32socket.AF_BT,e32socket.SOCK_STREAM,e32socket.BTPROTO_RFCOMM,e32socket.OBEX)
device =e32socket.bt_obex_discover()
print device
address=device[0]
print address
channel=device[1][u'OBEX Object Push']
print channel
e32socket.bt_obex_send_file(address,channel,u"E:23.txt")
for the mobile that will receive i used this code
import socket,e32socket,appuifw
socket=e32socket.socket(e32socket.AF_BT,e32socket.SOCK_STREAM,e32socket.BTPROTO_RFCOMM,e32socket.OBEX)
e32socket.bt_obex_receive(socket, u"E:23.txt")
I savesd first code in .py in an moible then i excuted using python interpreter,, first the bluetooth discovery menu appeares then i selected a mobile that has the mac address which is in the first code,, the error in the last line in that code ""socket.error:(2,'No such file or directory') "" this the error which i found
Can someone help me to solve this problem?
For one, "E:23.txt" is not a valid path to a file. Always remember your slashes, they are very important! Thus, you would change it from:
e32socket.bt_obex_send_file(address,channel,u"E:23.txt")
to
e32socket.bt_obex_send_file(address,channel,u"E:\\23.txt")
Also, I am not quite familiar with bt_obex_receive, but you would want to fix that path as well.
Additionally, you are importing the appuifw module without using it. Unless you plan on adding code that uses it, importing it is very inefficient.

Categories

Resources