vijay
vijay

Reputation:

python "'NoneType' object has no attribute 'encode'"

I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error:

> Traceback (most recent call last):  
> File "/home/vijay/ffour/ffour5.py",
> line 20, in <module>
>     myfeed()   File "/home/vijay/ffour/ffour5.py", line
> 15, in myfeed
>     sys.stdout.write(entry["title"]).encode('utf-8')
> AttributeError: 'NoneType' object has
> no attribute 'encode'

Upvotes: 6

Views: 27323

Answers (2)

David Locke
David Locke

Reputation: 18074

Lets try to clear up some of the confusion in the exception message.

The function call

sys.stdout.write(entry["title"])

Returns None. The ".encode('utf-8')" is a call to the encode function on what is returned by the above function.

The problem is that None doesn't have an encode function (or an encode attribute) and so you get an attribute error that names the type you were trying to get an attribute of and the attribute you were trying to get.

Upvotes: 5

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

> sys.stdout.write(entry["title"]).encode('utf-8')

This is the culprit. You probably mean:

sys.stdout.write(entry["title"].encode('utf-8'))

(Notice the position of the last closing bracket.)

Upvotes: 12

Related Questions