将数据附加到列表时出错。

时间:2017-03-02 08:26:55

标签: python csv file-io

这是我正在使用的代码 -

w = open("C:\\Users\\kp\\Desktop\\example.csv", "w+")
writer = csv.writer(w)
write_to = ""
for com in soup.find_all("div", {"class" : "commentlist first jsUserAction"}):
    for com1 in com.find_all("div", {"class" : "text"}):
        for com2 in com1.find_all("div" , {"class" : "user-review"}):
            u_name = com2.find("div", {"class" : "_reviewUserName"})
            u_rev = com2.find("p")
            print(u_name.text)
            print(u_rev.text)
            write_to.append(u_name.text)
            write_to.append(u_rev.text)

writer.write(write_to)

我的目标是将输出 - u_name.text和u_rev.text存储到“write_to”指向的文件中。

我收到以下错误 -

 File "C:/Users/kp/PycharmProjects/scrap_selenium/prog.py", line 72, in <module>
    write_to.append(str(u_name.text))
AttributeError: 'str' object has no attribute 'append'

1 个答案:

答案 0 :(得分:1)

问题是你正在尝试append到一个字符串。字符串没有append函数;这是一个列表功能。假设write_to应该是一个字符串,您可以使用以下方法之一来连接字符串。

您可以使用简单连接连接到字符串:

write_to += u_name.text

另一种选择是使用字符串函数join。这看起来像是:

write_to = "".join([write_to, u_name.text])

据报道,加入效率更高。使用join:

w = open("C:\\Users\\kp\\Desktop\\example.csv", "w+")
writer = csv.writer(w)
write_list = []
for com in soup.find_all("div", {"class" : "commentlist first jsUserAction"}):
    for com1 in com.find_all("div", {"class" : "text"}):
        for com2 in com1.find_all("div" , {"class" : "user-review"}):
            u_name = com2.find("div", {"class" : "_reviewUserName"})
            u_rev = com2.find("p")
            print(u_name.text)
            print(u_rev.text)
            write_list.append(u_name.text)
            write_list.append(u_rev.text)

write_to = "".join(write_list);
writer.write(write_to)

虽然看起来你错误地使用了csv writer。假设每行有两个以逗号分隔的值:u_name.textu_rev.text,您可以使用writerow写入文件,如下所示:

w = open("C:\\Users\\kp\\Desktop\\example.csv", "w+")
try:
    writer = csv.writer(w)
    for com in soup.find_all("div", {"class" : "commentlist first jsUserAction"}):
        for com1 in com.find_all("div", {"class" : "text"}):
            for com2 in com1.find_all("div" , {"class" : "user-review"}):
                u_name = com2.find("div", {"class" : "_reviewUserName"})
                u_rev = com2.find("p")
                print(u_name.text)
                print(u_rev.text)
                writer.write_row((u_name.text, u_rev.text))
finally:
    w.close()

这是一个链接,讨论了串联字符串的不同方法及其相对效率。 https://waymoot.org/home/python_string/