写入 csv 文件会在其自己的单元格中输出每个字母

import bs4 as bs

import urllib.request

import csv


source = 

   urllib.request.urlopen('http://www.thebest100lists.com/best100actors/').read()


soup = bs.BeautifulSoup(source, 'lxml')


for paragraph in soup.find_all('ol'):

    celebList = paragraph.text

    print(celebList)


with open('celebList.csv', 'w', newline='') as f:

    writer = csv.writer(f)


writer.writerow[soup.title.string]

for i in celebList:

    writer.writerow([i])

我正在玩漂亮的汤 4 从网站上的列表中抓取数据以将其输出到 .csv 文件。我已经正确地抓取了我正在寻找的数据,但是当我保存运行程序时,csv 文件在一行的自己的单元格中包含每个字母。我曾尝试将数据转换为字符串,我也尝试将 (i) 放在方括号中,但它对我不起作用。


aluckdog
浏览 231回答 3
3回答

繁星coding

我认为使用 a 标签的类选择器来获得一个没有间隙的列表然后用熊猫转储到 csv 会更有效from bs4 import BeautifulSoupimport requestsimport pandas as pdurl = 'http://www.thebest100lists.com/best100actors/'res = requests.get(url)soup = BeautifulSoup(res.content, "lxml")names = [name.text for name in soup.select('a.class1')]df = pd.DataFrame(names,columns=['Names'])df.to_csv(r'C:\Users\User\Desktop\Celebs.csv', sep=',', encoding='utf-8',index = False )

MMMHUHU

你可以这样做:celeblistsplit=celebList.split('\n')celeblistsplit进而:f=open('output.csv','w')for each in celeblistsplit:    if len(each)>0:        f.write(each)        f.write(',')        f.write('\n')f.close()结果文件:Robert De Niro,Al Pacino,Tom Hanks,Johnny Depp,Jack Nicholson,Marlon Brando,Meryl Streep,Leonardo DiCaprio,...

一只萌萌小番薯

import bs4 as bsimport urllib.requestimport csvsource = urllib.request.urlopen('http://www.thebest100lists.com/best100actors/').read()soup = bs.BeautifulSoup(source, 'lxml')celebList = []     # an empty list to store the textfor paragraph in soup.find_all('ol'):    celebList.append(paragraph.text)    # print(celebList)# file writing# print(celebList) # ["\nRobert De Niro\n\nAl Pacino\n\nTom Hanks\n\nJohnny .. ] celebList = map(lambda s: s.strip(), celebList)   # removing the leading spaces in the listcelebList = list(celebList)with open('celebList.csv', 'w') as file:    for text in celebList:        file.write(text)输出:Robert De NiroAl PacinoTom HanksJohnny DeppJack NicholsonMarlon Brando...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python