TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type - python

I need to find elements on a page by looking for text(), so I use xlsx as a database with all the texts that will be searched.
It turns out that it is showing the error reported in the title of the publication, this is my code:
search_num = str("'//a[contains(text()," + '"' + row[1] + '")' + "]'")
print(search_num)
xPathnum = self.chrome.find_element(By.XPATH, search_num)
print(xPathnum.get_attribute("id"))
print(search_num) returns = '//a[contains(text(),"0027341-66.2323.0124")]'
Does anyone know where I'm going wrong, despite having similar posts on the forum, none of them solved my problem. Grateful for the attention

Lot more quotes appear, Use python format() function to substitute the variable.
search_num ="//a[contains(text(),'{}')]".format(row[1])

Looks like you have extra quotes here
str("'//a[contains(text()," + '"' + row[1] + '")' + "]'")
Try changing to f"//a[contains(text(),'{row[1]}')]"

Related

Python double quotation syntax issue

This is my code:
for i in range(0, row_count):
if counter<row_count-1:
lines.append(""" var flightPlanCoordinates = [
{lat:""" + latitude[i] + """, lng: """ + longitude[i] + """}
{lat:""" + latitude[i + 1] + """, lng: """ + longitude[i + 1] + """}
];
""")
lines.append("""var flightPath"""+i+""" = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 5
});""")
counter += 1
I'm trying to figure out why this isn't compiling(I'm getting a syntax error). This is a string that will be part of the code to an html page. I want to create i flight path variables, each named flightpathi. So flightpath0, flightpath1 and so forth. When using """+i+""" or any other variable inside triple quotations on other lines, this works. I know this is probably something pretty simple that I'm overlooking, but I'm stuck and I'd appreciate any help!
Triple quotes are for multiline comments in python. I would use "var flightPath" + str(i). You may also want to look into enumerate for your loop. If you need the extra quotes as part of your string for some reason you need to escape them so they are not comments.

Make an Optional expression throw an error if it was present but didn't match

I'm using the PyParsing library to define my own SQL-like DSL. Here is the relevant part from it:
argument_separator = pp.Suppress(",")
brace_open = pp.Suppress("(")
brace_close = pp.Suppress(")")
argument_string = pp.quotedString.setParseAction(pp.removeQuotes)
keyword_author = pp.CaselessKeyword("author")
keyword_date = pp.CaselessKeyword("date")
function_matches = pp.CaselessLiteral("matches")
function_in = pp.CaselessLiteral("in")
function_between = pp.CaselessLiteral("between")
author_matches = pp.Group(keyword_author + function_matches + brace_open +
pp.Group(argument_string) +
brace_close)
author_in = pp.Group(keyword_author + function_in + brace_open +
pp.Group(argument_string + pp.OneOrMore(argument_separator + argument_string)) +
brace_close)
date_between = pp.Group(keyword_date + function_between + brace_open +
pp.Group(argument_string + argument_separator + argument_string) +
brace_close)
expression = pp.Optional(author_matches | author_in) & pp.Optional(date_between)
Examples:
# These all match:
author in("Lukas", "Timo", "Michae1")
author matches("hallo#welt.de")
date between("two days ago", "today")
author matches("knuth") date between("two days ago", "today")
# This does (and should) not.
date between(today)
The last expression doesn't match but doesn't throw an exception either. It just returns an empty result.
My goal: A "query" in my DSL consists of multiple expressions of the form
[column] [operator]([parameter],...)
No doublets are allowed. Furthermore, all possible expressions are optional (so an empty query is perfectly legal).
My problem: The current approach doesn't throw an error if one of these expressions is malformed. Because they are all Optional, if they don't match exactly, they're just ignored. That is confusing to the user, since he doesn't get an error, but the result is wrong.
So, what I need is an expression that is optional (so can be completely omitted), but will throw a ParseException, if it was malformed.
Try setting parseAll to True when parsing each line, e.g. expression.parseString(line, parseAll=True). This will throw a ParseException exception if the entire line wasn't matched.
See the "Using the pyparsing module" page for a bit more info.

Trouble inputting interger values into an SQL statement within ArcGIS

So I am defining a function for use in a ArcGIS tool that will verify attributes, catch errors, and obtain user input to rectify those error. I want the tool to select and zoom to the segment that is being currently assessed so that they can make an informed decision. This is what I have been using, and it works well. But the CONVWGID is the variable that will be changing, and I'm not sure how to input that variable into an SQL statement without causing errors.
This is how I had tested the logic:
def selectzoom():
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", " [CONVWGID] = 10000001")
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
Then I needed to work the variable into the function in order to accept different CONVWGID values, which gives me a Runtime/TypeError that I should have known would happen.
Runtime error -
Traceback (most recent call last): - File "string", line 1, in module - TypeError: cannot concatenate 'str' and 'int' objects
def selectzoom(convwkgid):
delimfield = '" [CONVWGID] = ' + convwkgid + ' "'
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", delimfield)
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
And when I alter the delimfield line to change the integer into a string, it selects all of the attributes in the entire feature class. Not just the one that had been passed via the function call.
delimfield = '"[CONVWGID] = ' + str(convwkgid) + '"'
I'm not amazing with SQL and maybe I'm missing something basic with this statement, but I can't figure out why it won't work when I'm basically giving it the same information:
"[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"'
It turned out to be the extra inclusion of Double quotes inside of my single quotes that raised this problem.
Thanks to #Emil Brundage for the help!
Let's say convwkgid = 10000001
'"[CONVWGID] = ' + str(convwkgid) + '"' doesn't equal "[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"' would actually be '"CONVWGID] = 10000001"'
Try instead:
'[CONVWGID] = ' + str(convwkgid)

Inserting unicode MYSQL results within Python

if results:
for line in results:
print line[0] + ' - ' + line[1]
I need to insert a '-' between line[0] and line[1], but when I enter the above code, I get the error message 'coercing to Unicode: need string or buffer, int found'. Any suggestions on a way around this?
Thanks in advance.
the problem is that line[0] or line[1] holding an int number.
by using "+" and 'some string' you are telling python please append to the string the next string, but you have an int so the interpreter is raising a problem.
try to use:
if results:
for line in results:
print str(line[0]) + ' - ' + str(line[1])
"+" note in python will change it's "action" when meeting different data types. it's a very powerful feature but as default it cannot add different datatypes.

Reading data from Excel sheets and building SQL statements, writing to output file in Python

I have an excel book with a couple of sheets. Each sheet has two columns with PersonID and LegacyID. We are basically trying to update some records in the database based on personid. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying to learn Python, I thought I would try this in Python. I used xlrd module and I was able to print update statements. below is my code:
import xlrd
book = xlrd.open_workbook('D:\Scripts\UpdateID01.xls')
sheet = book.sheet_by_index(0)
myList = []
for i in range(sheet.nrows):
myList.append(sheet.row_values(i))
outFile = open('D:\Scripts\update.txt', 'wb')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
Two problems - when I read the output file, I see the LegacyID printed as float. How do I get rid of .0 at the end of each id? Second problem, python doesn't print each update statement in a new line in the output text file. How to I format it?
Edit: Please ignore the format issue. It did print in new lines when I opened the output file in Notepad++. The float issue still remains.
Can you turn the LegacyID into ints ?
i[1] = int(i[1])
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
try this..
# use 'a' if you want to append in your text file
outFile = open(r'D:\Scripts\update.txt', 'a')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i[1]), str(i[0])))
Since you are learning Python (which is very laudable!) you should start reading about string formatting in the Python docs. This is the best place to start whenever you have a question light this.
Hint: You may want to convert the float items to integers using int().

Categories