python历程——openpyxl与excel
在运行以下代码时,将文本保存为xlxs,一直在失败,试试之前的csv格式,成功,报错
import requests from lxml import etree url = 'https://book.douban.com/subject/1084336/comments/' r = requests.get(url).text s = etree.HTML(r) # print( s.xpath('//*[@id="comments"]/ul/li[1]/div[2]/p/text()')) file = s.xpath('//div[@class="comment"]/p/text()') # ... # with open('pinglun.txt','w',encoding='utf-8') as f: # for i in file: # print(i) # f.write(i) # ... import pandas as pd import numpy as np df = pd.DataFrame(file) print(df.head()) # df.to_csv('pinglun1.csv',encoding='utf_8_sig') df.to_excel('pinglun.xlsx')错误:
原因:excel是2016版本,所以需要openpyxl库,而自己并没有安装,所以根据这篇文章http://openpyxl.readthedocs.io/en/default/安装了openplxy的whl文件,但是运行还是不可以,最后在 pycharm->file->settings->project interpreter中寻找openpyxl进行添加,再在代码from lxml import etree 之后添加 from openpyxl import Workbook 进行运行,成功。