codygman
codygman

Reputation: 832

TypeError: cannot concatenate 'str' and 'instance' objects (python urllib)

Writing a python program, and I came up with this error while using the urllib.urlopen function.

Traceback (most recent call last):
File "ChurchScraper.py", line 58, in <module>
html = GetAllChurchPages()
File "ChurchScraper.py", line 48, in GetAllChurchPages
CPs = CPs + urllib.urlopen(url)
TypeError: cannot concatenate 'str' and 'instance' objects


 url = 'http://website.com/index.php?cID=' + str(cID)
        CPs = CPs + urllib.urlopen(url)

Upvotes: 2

Views: 8427

Answers (4)

Satwik
Satwik

Reputation: 111

What is CPs? It looks like it is a string. urlopen will return an instance of a file-like object, not a string. See - http://docs.python.org/library/urllib.html.

The error is not thrown from the urlopen, but because you are trying to concatenate a string with an object instance.

Upvotes: 0

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26128

The problem is in this line: CPs = CPs + urllib.urlopen(url) I assume CPs is a string however urllib.urlopen(url) returns a file like object.

If you want to join the contents of the file at url with CPs then you need to do something like this: CPs = CPs + urllib.urlopen(url).read().

Upvotes: 1

Arkaitz Jimenez
Arkaitz Jimenez

Reputation: 23198

urllib.urllopen doesn't return a string, it returns an object
doc

If all went well, a file-like object is returned.

Upvotes: 2

unutbu
unutbu

Reputation: 880269

urlopen(url) returns a file-like object. To obtain the string contents, try

CPs = CPs + urllib.urlopen(url).read()

Upvotes: 6

Related Questions