The following code gives the error:
line 19, in modifyXML
self.PreFlopCallPower.text = 'NEW VALUE'
AttributeError: 'str' object has no attribute 'text'
The problem seems to be that self.PreFlopCallPower is only a string and not an elementTree object, even though my example is very similar to the example given on the python etree documentation: self.PreFlopCallPower = entry.find('PreFlopCallPower').text. How can I fix this? I can't see what I'm doing different to the update example listed here: https://docs.python.org/2/library/xml.etree.elementtree.html
import xml.etree.ElementTree as xml
class XMLHandler(object):
def __init__(self,StrategyName):
self.readXML(StrategyName)
self.modifyXML()
def readXML(self, StrategyName):
self.Template = StrategyName
self.tree = xml.parse('strategies.xml')
self.root = self.tree.getroot()
for entry in self.root.findall('Strategy'):
if entry.get('name') == StrategyName:
self.PreFlopCallPower = entry.find('PreFlopCallPower').text
def modifyXML (self):
self.PreFlopCallPower.text = 'NEW VALUE' # ---ERROR OCCURS HERE---
self.PreFlopCallPower.set('updated', 'yes')
self.tree.write('output.xml')
X=XMLHandler('Strategy305PP')
In this line, you're storing the text of the node (hence have a str):
self.PreFlopCallPower = entry.find('PreFlopCallPower').text
Drop the .text to store the node itself:
self.PreFlopCallPower = entry.find('PreFlopCallPower')
Related
I was trying to work with TableWidgets on Python and I ran into an issue.
I wanted to check whether the table is filled or not (with str of course).
def add_table (self):
self.kala = self.comboBox.currentText()
self.code_kala = self.comboBox.currentIndex()
self.vahed = self.comboBox_2.currentText()
list_e = []
for i in list(range(10)):
#self.tab = self.tableWidget.item(i,0)
if self.tableWidget.item(i,0).text() != '':
#if self.tab.text() !='':
list_e.append(i)
else:
pass
self.ROW = len(list_e)
self.tableWidget.setItem(self.ROW,0,QTableWidgetItem(self.kala))
self.tableWidget.setItem(self.ROW,1,QTableWidgetItem(str(self.code_kala)))
self.tableWidget.setItem(self.ROW,2,QTableWidgetItem(str(self.vahed)))
and I don't know why I keep getting this error:
NoneType' object has no attribute 'text'
Does anyone know how to solve it?
Also, I know this code doesn't have any problem (I got good results with the same code in another project) but as cmd said:
File "D:\**\***\*****\*******\*\*************.py", line 1755, in add_table
if self.tableWidget.item(i,0).text() != '':
AttributeError: 'NoneType' object has no attribute 'text'
It seems that the table widget might contain 'None' values, so you have to expect them to pop up. Instead of doing this:
if self.tableWidget.item(i,0).text() != '':
do that:
thing = self.tableWidget.item(i,0)
if thing is not None and thing.text() != '':
# do stuff with thing
I am trying to extract the value of an attribute from a tag (in this case, TD). The code is as follows (the HTML document is loaded correctly; self.data contains string with HTML data, this method is part of a class):
def getLine (self):
dat = BeautifulSoup(self.data, "html.parser")
tags = dat.find_all("tr")
for current in tags:
line = current.findChildren("td", recursive=False)
for currentLine in line:
# print (currentLine)
clase = currentLine["class"] # <-- PROBLEMATIC LINE
if clase is not None and "result" in clase:
valor = Line()
valor.name = line.text
The error is in the line clase = currentLine["class"]. I just need to check the tag element has this attribute and do things in case it has the value "result".
File "C:\DataProgb\urlwrapper.py", line 43, in getLine
clase = currentLine["class"] #Trying to extract attribute class
\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 1519, in __getitem__
return self.attrs[key]
KeyError: 'class'
It should work, because it's just an element. I don't understand this error. Thanks.
Main issue is that you try to access the attribute key directly, what will return a KeyError, if the attribute is not available:
currentLine["class"]
Instead use get() that will return in fact of a missing attribute None:
currentLine.get("class")
From the docs - get(key\[, default\]):
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
Trying to work with BeautifulSoup but I'm getting this error:
AttributeError: 'NoneType' object has no attribute 'string'
The problem is with this line
_a = _dev.find('a')
Here is my code:
for _dev in devs:
_d = _dev.find('div')
authors.append(_d.text.strip())
_a = _dev.find('a')
if not _a.string is None:
names.append(_a.text.strip())
if 'href' in _a.attrs.keys():
urls.append(_a.get('href'))
How can I fix this?
The problem is most likely with this line if not _a.string is None:.
If _dev.find('a') does not find what you're looking for it returns None. Since you assigned the value to _a, that means you are calling None.string on that line, which will definitely raise an error.
Change that line to this:
if _a and not _a.string is None:
I'm aware that there are similar problems to mine but I tried those solutions and they don't work.
I have text field:
self.tMail = QtGui.QPlainTextEdit(self.centralwidget)
self.tMail.setGeometry(QtCore.QRect(50, 270, 451, 75))
self.tMail.setAccessibleName(_fromUtf8(""))
self.tMail.setInputMethodHints(QtCore.Qt.ImhNone)
self.tMail.setPlainText(_fromUtf8(""))
self.tMail.setOverwriteMode(False)
self.tMail.setObjectName(_fromUtf8("tMail"))
And i want to add them to the variable string by:
def handleButton(self):
timeString = self.tCzas.text()
mailString = self.tMail.text()
IDString = self.tID.text()
teamString = self.tTeam.text()
print(timeString)
print(mailString)
print(IDString)
print(teamString)`
also I tried:
mailString = self.tMail.plainText()
and I always get an error:
AttributeError: 'QPlainTextEdit' object has no attribute '...'
Why?
QPlainTextEdit doesn't have a text() function. try using the toPlainText() function:
def handleButton(self):
timeString = self.tCzas.toPlainText()
mailString = self.tMail.toPlainText()
IDString = self.tID.toPlainText()
teamString = self.tTeam.toPlainText()
print(timeString)
print(mailString)
print(IDString)
print(teamString)
I am trying to retrieve a tags using boto3 but I constantly run into the ListIndex out of range error.
My Code:
rds = boto3.client('rds',region_name='us-east-1')
rdsinstances = rds.describe_db_instances()
for rdsins in rdsinstances['DBInstances']:
rdsname = rdsins['DBInstanceIdentifier']
arn = "arn:aws:rds:%s:%s:db:%s"%(reg,account_id,rdsname)
rdstags = rds.list_tags_for_resource(ResourceName=arn)
if 'MyTag' in rdstags['TagList'][0]['Key']:
print "Tags exist and the value is:%s"%rdstags['TagList'][0]['Value']
The error that I have is:
Traceback (most recent call last):
File "rdstags.py", line 49, in <module>
if 'MyTag' in rdstags['TagList'][0]['Key']:
IndexError: list index out of range
I also tried using the for loop by specifying the range, it didn't seem to work either.
for i in range(0,10):
print rdstags['TagList'][i]['Key']
Any help is appreciated. Thanks!
You should iterate over list of tags first and compare MyTag with each item independently:
something like that:
if 'MyTag' in [tag['Key'] for tag in rdstags['TagList']]:
print "Tags exist and.........."
or better:
for tag in rdstags['TagList']:
if tag['Key'] == 'MyTag':
print "......"
I use function have_tag to find tag in all modul in Boto3
client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']
if instances:
for i in instances:
arn = i['DBInstanceArn']
# arn:aws:rds:ap-southeast-1::db:mydbrafalmarguzewicz
tags = client.list_tags_for_resource(ResourceName=arn)['TagList']
print(have_tag('MyTag'))
print(tags)
Function search tags:
def have_tag(self, dictionary: dict, tag_key: str):
"""Search tag key
"""
tags = (tag_key.capitalize(), tag_key.lower())
if dictionary is not None:
dict_with_owner_key = [tag for tag in dictionary if tag["Key"] in tags]
if dict_with_owner_key:
return dict_with_owner_key[0]['Value']
return None