将 CSV 文件写入单元格

我当前的代码将 CSV 写入多个单元格(请参阅屏幕截图)

http://img2.mukewang.com/61c818760001c01b04000458.jpg

from bs4 import BeautifulSoup

import csv

import urllib

url = 'https://www.bhphotovideo.com/c/product/1346734-REG/canon_eos_6d_mark_ii.html'


page = urllib.request.urlopen(url)

soup = BeautifulSoup(page,'lxml')

content = soup.find('div', class_='js-productHighlights product-highlights c28 fs14 js-close')

bullets = content.find_all('li', class_='top-section-list-item')

csv_file = open('book2.csv', 'w')

csv_writer = csv.writer(csv_file)

csv_writer.writerow (['headline'])

for bullet in bullets:

     headline = (bullet.string)

     csv_writer.writerow ([headline])


csv_file.close()

如何将excel写入单个单元格?


所需的输出将是 - 单元格 A1 将包含变量“标题”包含的所有文本。


慕的地6264312
浏览 307回答 1
1回答

呼啦一阵风

而不是bullets像现在这样遍历所有内容并将每个内容写入 csv 文件:for bullet in bullets:     headline = (bullet.string)     csv_writer.writerow ([headline])您可能应该只写一行,其中包含经过消毒的bullets变量内容。不完全确定您的内容是什么样的,但请尝试以下操作:# your other code...bullets = content.find_all('li', class_='top-section-list-item')csv_file = open('book2.csv', 'w')csv_writer = csv.writer(csv_file)csv_writer.writerow (['headline'])# don't loop, instead join values with new linecsv_writer.writerow(['\015'.join([bullet.string for bullet in bullets])])    csv_file.close()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python