Python 从html文档保存表

Python 从html文档保存表,python,Python,我尝试将文档中的表保存为目录下的文件,如下所示: 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 Trac

我尝试将文档中的表保存为目录下的文件,如下所示:

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
但是,我不断得到如下错误:

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
回溯(最近一次呼叫最后一次):
文件“”,第4行,在
fileref.write(表字符串)
TypeError:必须是str,而不是bytes
我正在使用Python 3.3并安装了lxml-3.0.1.win32-py3.3。‌exe


如何修复此错误

lxml的
tostring
方法返回一个bytestring(
bytes
),因为它已经被编码。这是必要的,因为XML/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

您应该更正您的消息,使代码更具可读性。是的,我甚至不知道如何接受注释。“我为我的愚蠢感到抱歉,我也为所有的评论者感到抱歉。”吉米。谢谢@Jimmy,评论和答案一样是不可接受的,它们只是用来澄清问题的。