TypeError: coercing to Unicode: need string or buffer, ResultSet found

TypeError: coercing to Unicode: need string or buffer, ResultSet found

我想将维基百科上的信息 table 保存到 csv 文件中。搜索时,我在 this page 中找到了使用 BeautifulSoup 将 table 项写入文件的代码。

略有不同,我只想将信息获取到我计算机上的文件中。我想从这个 wiki page 得到 table。我最终得到了这段代码:

from bs4 import BeautifulSoup
import urllib2

wiki = "https://en.wikipedia.org/wiki/List_of_minor_planets:_1001%E2%80%932000"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)

Name = ""
designation = ""
date = ""
site = ""
discoverer = ""
table = soup.find("table")

f = open('output.csv', 'w')

for row in table.findAll("tr"):
    cells = row.findAll("td")
    #For each "tr", assign each "td" to a variable.
    if len(cells) == 5:
        Name = cells[0].find(text=True)
        designation = cells[1].findAll(text=True)
        date = cells[2].find(text=True)
        site = cells[3].find(text=True)
        discoverer = cells[4].find(text=True)

        for x in range(len(site)):
            write_to_file = (site + ";" + Name + ";" + designation + ";" + 
                             date + ";" + discoverer + "\n")
            print write_to_file
            f.write(write_to_file)

f.close()

唯一的区别是,我没有 "sortable table" 所以我从代码中删除了那部分,我有 5 列。

但是代码returns出现如下错误:

TypeError: coercing to Unicode: need string or buffer, ResultSet found

我认为它与代码中的“\n”有关,这就是我得到错误的地方。

您认为这个问题是什么,我该如何克服它?

通过将 write_to_file 转换为 str(write_to_file) 有助于 printf.write

它与'\n'无关,罪魁祸首是这一行:

designation = cells[1].findAll(text=True)

注意这一行如何使用 findAll 而其他行使用 find.

findAll returns 一个列表(实际上是一个 ResultSet),即使它只找到一个匹配项。稍后,当您构建 write_to_file 字符串时,当您尝试连接部分字符串和 designation(即 ResultSet)时会引发错误。

findAll 替换为 find 并且有效(最终编码错误除外)