我当前的代码将 CSV 写入多个单元格(请参阅屏幕截图)from bs4 import BeautifulSoupimport csvimport urlliburl = '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 将包含变量“标题”包含的所有文本。
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
而不是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()
添加回答
举报
0/150
提交
取消
