我当前的代码将CSV写入到多个单元格中(请参见屏幕截图)
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将具有变量“标题”保留的所有文本。
谢谢!
答案 0 :(得分:0)
与其像现在一样循环遍历所有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 line
csv_writer.writerow(['\015'.join([bullet.string for bullet in bullets])])
csv_file.close()