1

次のように、ドキュメントのテーブルをディレクトリの下のファイルとして保存しようとしました。

for table in tables:
    tableString = html.tostring(table)
    fileref=open('c:\\Users\\ahn_133\\Desktop\\appleTables\\Apple-' + str(count) + '.htm', 'w')
    fileref.write(tableString)
    fileref.close()
    count+=1

しかし、次のようなエラーが発生し続けます。

Traceback (most recent call last):
  File "<pyshell#27>", line 4, in <module>
    fileref.write(tableString)
TypeError: must be str, not bytes

Python 3.3を使用していて、lxml-3.0.1.win32-py3.3.‌exeをインストールしています

このエラーを修正するにはどうすればよいですか?

4

1 に答える 1

2

lxmlのtostringメソッドは、すでにエンコードされているため、バイト文字列( )を返します。bytesXML / HTMLドキュメントは独自のエンコーディングを指定できるため、これが必要です。

バイナリモードでファイルを開くだけです。

for table in tables:
    tableString = html.tostring(table)
    filename = r'c:\Users\ahn_133\Desktop\appleTables\Apple-' +str(count)+ '.htm'
    with open(filename, 'wb') as fileref:
        #                 ^
        fileref.write(tableString)
    count+=1
于 2012-11-22T16:15:50.197 に答える