TypeError:无法连接'str'和'instance'对象(python urllib)

时间:2009-11-02 12:14:58

标签: python urllib

编写python程序,我在使用urllib.urlopen函数时想出了这个错误。

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)

4 个答案:

答案 0 :(得分:6)

urlopen(url)返回类似文件的对象。要获取字符串内容,请尝试

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

答案 1 :(得分:2)

urllib.urllopen不返回字符串,它返回一个对象
doc

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

答案 2 :(得分:1)

问题在于这一行:CPs = CPs + urllib.urlopen(url)我认为CPs是一个字符串,但是urllib.urlopen(url)返回一个像object这样的文件。

如果您想要urlCPs加入文件内容,则需要执行以下操作:CPs = CPs + urllib.urlopen(url).read()

答案 3 :(得分:0)

什么是CP?它看起来像是一个字符串。 urlopen将返回类文件对象的实例,而不是字符串。见 - http://docs.python.org/library/urllib.html

错误不会从urlopen中抛出,而是因为您尝试将字符串与对象实例连接起来。

相关问题