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

4

2

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)
Scintillometer answered 2/11, 2009 at 12:14 Comment(2)
You've snipped out the code and traceback in way that's really hard to read. Please show the code with proper indentation separate from the traceback.West
@Codygman: Thanks -- while nice -- aren't the way StackOverflow works. Please go to the answer you accepted. Please click the checkmark to indicate that you accepted the answer.West
B
6

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

CPs = CPs + urllib.urlopen(url).read()
Bottomless answered 2/11, 2009 at 12:18 Comment(1)
Thanks ~unutbu! Code worked perfectly.. i had the same code about 20 lines up in the program :S It's a bit late though (6:22) and it was easy to overlook. Thanks so much for the fast answer though!Scintillometer
C
2

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

If all went well, a file-like object is returned.
Confect answered 2/11, 2009 at 12:19 Comment(1)
Thanks for the fast answer Arkaitz! I can't believe I made that silly error.. one of those things you keep looking at and wonder what happened!Scintillometer
F
1

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().

Fabric answered 2/11, 2009 at 12:21 Comment(0)
O
0

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.

Oligosaccharide answered 2/11, 2009 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.