AttributeError: "str' object has no attribute 'text - python

I make script for shopify cart since it is impossible to purchase manually, when I ran the script to my command prompt,
it says ,
line 109, in AttributeError: "str' object has no attribute
'text
Scrape Product Info based on selected colors
if blue and cinder:
productInfo(urlBlueResponse.text)
productInfo(urlCinderResponse.text)
elif blue:
productInfo(urlBlueResponse.text)
elif cinder:
productInfo(urlCinderResponse.text)
else:
print(Fore.RED + timestamp
I was told it was from a capitalization mismatch, can somebody please explain this to me. I am new to coding and I want to learn all I can.

Based on the error message, either urlBlueResponse or urlCinderResponse (or both) are a string datatype. The way you are using them, it appears you expect these to be objects which have a text attribute. The error message is telling you that they're str objects and don't have text attributes.

This error happened when you tried to access an attribute on a string object -- .text -- that does not exist as an element on that object.
It looks like your code is working with HTTP request and response objects of some kind: urlBlueResponse
It is plausible that you got an error or some other unexpected behavior in the request/response cycle that resulted in one of the response objects returning a str (string) type instead of a response object with a text attribute. I suggest you handle the exception with a try/except block:
try:
if blue and cinder:
productInfo(urlBlueResponse.text)
productInfo(urlCinderResponse.text)
elif blue:
productInfo(urlBlueResponse.text)
elif cinder:
productInfo(urlCinderResponse.text)
else:
print(Fore.RED + timestamp)
except AttributeError as e:
#exception handler logic goes here
print("got exception: ")
print(e)
#if error indicates your request is recoverable then do so:
if recoverable(e):
do_request(again)
#if error is unrecoverable, decorate it and reraise it
#(See *Link)
# or just reraise it:
raise(e)
*Link: (Re-raise exception with a different type and message, preserving existing information)

urlBlueResponse = eval(urlBlueResponse)

Related

"'NoneType' object has no attribute ..." when object checked not to be None?

How is possible that in Python if they first check if some object is not None (if popResult:) they use that object in else branch to get its Attribute messages list?
I am not an expert for Python but I am using some already very reliable GitHub script -
https://github.com/NavicoOS/ac2git/
def TryPop(self, streamName, transaction):
logger.debug("**** entered TryPop method *******")
for i in range(0, 2):
popResult = accurev.pop(verSpec=streamName, location=self.gitRepo.path,elementList='.')
if popResult:
break
else:
logger.error("accurev pop failed:")
for message in popResult.messages:
if message.error is not None and message.error:
logger.error(" {0}".format(message.text))
else:
logger.info(" {0}".format(message.text))
return popResult
With this script I got the following error:
File "/home/ac2git/ac2git.py", line 965, in TryPop
for message in popResult.messages:
AttributeError: 'NoneType' object has no attribute 'messages'
Again - as this is one of the basic methods for this project, I really doubt that developers made such a beginner's mistake, because this project has been used in many years for migrating from some other SCM to Git, but on the other hand I really cannot see how they could use object (popResult) to retrieve its attribute if that object is None? Is it possible to put something like this in else branch?
Could you please provide me guidance for this or correction of the code if needed?
You have explicitly check if popResult is None before trying to access its members:
def tryPop(self, streamName, transaction):
logger.debug("**** entered TryPop method *******")
for i in range(0, 2):
popResult = accurev.pop(verSpec=streamName, location=self.gitRepo.path,elementList='.')
if popResult is None:
print("popResult is None !")
continue
elif popResult:
break
else:
logger.error("accurev pop failed:")
for message in popResult.messages:
if message.error is not None and message.error:
logger.error(" {0}".format(message.text))
else:
logger.info(" {0}".format(message.text))
return popResult
But actually popResult being None is just a symptom of some other error you made and the above does not cure the original cause which I'm unsure of - try using an absolute, full path for elementList.

Python Selenium sending keys to a textfield

Im writing a google forms submitter and I'm having problems with the textfield-type questions.
Basically I am using:
textfield = question.find_element_by_class_name("quantumWizTextinputPaperinputInput")
to find the textfield and then the problems start coming in. The type of "textfield" is:<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="1b49148e-2a24-4efb-b3a5-e84be92223ae", element="3b437c8b-8d05-4410-8047-bcac9ea81f0f")>
and when I want to call .send_keys(string) on it it says that Exception has occurred: AttributeError 'list' object has no attribute 'send_keys'
So basically it says that the element returned is a list (noenetheless that type() returns a firefoxwebdriver element type).
So if I try to go with textfield[0] or textfield[1] etc... it of course throws an error that a FirefoxWebDriver is not subscribable.
What the frick?
Here's the block of code:
buttons = question.find_elements_by_class_name("appsMaterialWizToggleRadiogroupRadioButtonContainer")
buttons2 = question.find_elements_by_class_name("quantumWizTogglePapercheckboxInnerBox")
try:
textfield = question.find_element_by_class_name("quantumWizTextinputPaperinputInput")
except:
print("not found")
textfield = []
pass
And then below to send keys into it:
if len(buttons) == 0 and len(buttons2) == 0:
print(textfield)
textfield.send_keys("lol spam")
try:
textfield = question.find_element_by_class_name("quantumWizTextinputPaperinputInput")
except:
print("not found")
textfield = []
pass
The problem lies within this snippet. If textfield, or to be more specific the class_name quantumWizTextinputPaperinputInput can't be found, Python continues to evaluate the except block. Within there you stated textfield = [] - that's the reason for your problems:
Exception has occurred: AttributeError 'list' object has no attribute
'send_keys' So basically it says that the element returned is a list
(noenetheless that type() returns a firefoxwebdriver element type). So
if I try to go with textfield[0] or textfield[1] etc... it of course
throws an error that a FirefoxWebDriver is not subscribable.
You can't send send_keys to a list.
List is empty, hence a textfield[0] should throw IndexError.
A solution to this problem is to find the proper class_name. Without a HTML code we can't help you to do that.

How to list all the value of one node attributes with Maya python?

I am trying to list all the attributes and their value for one node (from Mash network), but I got an error when the attribute has no value, even if I use try/except loop
attributes = cmds.listAttr('MASH_A_Repro')
for attribute in attributes:
myAttr='MASH_A_Repro.'+attribute
try :
print 'Attribute %s Value %s' % (attribute, cmds.getAttr(myAttr) )
except KeyError:
print 'erreur'
Error: RuntimeError: file line 10: Message attributes have no data values. #
In this case, the first attribute is "Message" and has no value. How can I bypass this one ?
You want to work around message attributes -- as the error says they don't have data.
This will do keep you from blowing up:
import maya.cmds as cmds
for item in cmds.listAttr('polyPlane1'):
try:
print cmds.getAttr('polyPlane1.' + item)
except RuntimeError:
pass
But you'll still get an annoying error printout. You can do a cheap precheck by limiting your listAttr call to writeable attributes:
for item in cmds.listAttr('polyPlane1', w=True):
try:
print item, cmds.getAttr('polyPlane1.' + item)
except RuntimeError:
pass
use flag: hasData=True
list only attributes that have data (all attributes except for message attributes)
attrsList = cmds.listAttr(camShape, keyable=True, visible=True, hasData=True)

Python intermittently throws "AttributeError: 'NoneType' object has no attribute 'get'" on the same dictionary

I have a nested dictionary like so:
mail = {
'data': { 'from': {'text': '123#example.com'}}
# some other entries...
}
I'm trying to copy from value using following code:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from').get('text')
The second line throws the exception:
AttributeError: 'NoneType' object has no attribute 'get'
The strange thing is, this only happens sometimes. If I add a print statement just before the second line like:
data = mail.get('data')
print(type(data.get('from')))
new_dict['parse']['from'] = data.get('from').get('text')
The error disappears and I get <class 'dict'> as expected. If I remove the print statement, it works sometimes and other times it throws the error. Nothing else changes in the code or data. The reason I'm using get() is to retrieve value safely in case the key is missing.
In the call data.get('from').get('text'), if data does not contain the key 'from', it will return None. None.get('text') raises then the exception you see, because a None object has no get method (of course).
The way around this is to pass in a better default-object than None (the default default-object), which has the get method. That would be an empty dictionary, {}:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from', {}).get('text')

"object of type 'NoneType' has no len()" when using pusher with Django

I have implemented a very basic and by-the-tutorial Pusher triggers in my django app.
At first it worked great, but after a few commits I ran into the following exception:
"object of type 'NoneType' has no len()"
Out of the second of the following lines:
p = pusher.Pusher()
p[page_key].trigger('page_update', {'msgid' : message.id})
Different or an empty dict produced same result, same as changing page_key to string instead of unicode - nothing.
Also note that type() of p and p.trigger gives logical results, and they're definitely not None.
This line WORKS IN SOME CASES (which I have no clue what so special about them) and has worked in the past as I've mentioned, yet I can't figure out what am I doing wrong.
It seems that none of the last commits have anything to do with Pusher, so I'm helpless. Searching the web for this exception wasn't fruitful at all and in general there's not enough documentation regarding to django + Pusher.
It is probably something else that I'm doing wrong but I have no clue where to start looking.
Any help will be most appreciated.
Traceback:
79. p[page_key].trigger('page_update', {'msgid' : message.id})
File "/usr/local/lib/python2.7/dist-packages/pusher/__init__.py" in trigger
41. status = self.send_request(self.signed_query(event, json_data, socket_id), json_data)
File "/usr/local/lib/python2.7/dist-packages/pusher/__init__.py" in signed_query
54. signature = hmac.new(self.pusher.secret, string_to_sign, hashlib.sha256).hexdigest()
File "/usr/lib/python2.7/hmac.py" in new
133. return HMAC(key, msg, digestmod)
File "/usr/lib/python2.7/hmac.py" in __init__
68. if len(key) > blocksize:
Exception Type: TypeError at /sphere/comment
Exception Value: object of type 'NoneType' has no len()
self.pusher.secret is None there instead of a string. Are your settings for pusher not getting picked up?

Categories

Resources