###前提・実現したいこと
Python日本語CSV出力時のunicode問題で困っています。
python 2.7系であるサイトのテーブルの情報をスクレイピングし、csvに書き出そうとしています。Beautiful Soupを使ってスクレイピングしようとしているのですが、unicodeの問題でうまくCSVに出力できません。
###発生している問題・エラーメッセージ
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
###該当のソースコード
python
1# coding: UTF-8 2import urllib2 3import requests 4import csv 5from bs4 import BeautifulSoup 6 7soup = BeautifulSoup(res.text, "html.parser") 8trs = soup.find_all('table', attrs={'class': 'listtable'})[1] 9list = [] 10 11for tr in trs.findAll('tr')[1:]: 12 row = [] 13 no = tr.findAll('td')[0].string 14 name = tr.findAll('td')[1].string 15 if name is None: 16 name = "" 17 status = tr.findAll('td')[2].string 18 mvDate = tr.findAll('td')[9].string 19 if mvDate is None: 20 mvDate = "" 21 row.append(no) 22 row.append(name) 23 row.append(status) 24 row.append(mvDate) 25 26 list.append(row) 27 28f = open('some.csv', 'w') 29writer = csv.writer(f, lineterminator='\n') 30writer.writerows(list) 31f.close() 32 33#printすると以下のような出力結果になります。 34print str(list).decode("unicode-escape") 35[[u'001', u'佐々木', u'滞在', ''], [u'300A', u'田中', u'滞在', ''], [u'600B', u'山田', u'退居', u'2000/02/10'], [u'100C', u'加藤', u'滞在', ''], [u'123', u'中田', u'滞在', '']
python csv unicodeでググっていくつか参照して見てみましたが、あまりうまくいかずご質問させて頂きました。decodeして出力すると上記のような配列が返ってきます。よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー