类型错误:不能连接“STR”和“实例”对象(蟒蛇的urllib)

StackOverflow https://stackoverflow.com/questions/1660954

  •  12-09-2019
  •  | 
  •  

编写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)
有帮助吗?

解决方案

的urlopen(URL)返回一个类文件的对象。为了获得字符串的内容,尝试

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

其他提示

urllib.urllopen不返回一个字符串,它返回一个对象,点击 DOC

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

问题是在这条线:CPs = CPs + urllib.urlopen(url)我假定CPs然而urllib.urlopen(url)字符串返回像对象的文件

如果你想在与url CPs加入了文件的内容,那么你需要做这样的事情:CPs = CPs + urllib.urlopen(url).read()

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

该错误不从的urlopen抛出,而是因为你试图连接具有一个对象实例的字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top