TypeError:在编写解析结果时需要一个字符缓冲区对象

时间:2013-07-02 12:34:23

标签: python html-parsing

import requests
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        return data

def criapagina():
    r = requests.get('http://shadowcores.twifysoft.net/character.php?name=Sonda+Aquatica')
    fo = open('teste.txt', 'w')
    fo.write(r.content)
    print fo.readline
    fo.close()

def lepagina():
    fo = open('teste.txt', 'r+')
    for line in fo:
        parser = MyHTMLParser()
        fo.write(parser.feed(line))
        fo.close()


lepagina()

我想解析html并在读取正确的行后写入文件名称:Sonda Level:bla bla 但我甚至无法将其保存在文件中,因为我收到错误:TypeError:期望一个字符缓冲区对象

1 个答案:

答案 0 :(得分:1)

您收到错误,因为HTMLParser.feed()返回None;你不能将None写入文件:

>>> open('/tmp/test.txt', 'w').write(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

您对teste.txt的读写尝试将失败;你应该将文件对象都视为迭代器(for line in fo)并期望能够写入文件。文件迭代器使用预读缓冲区,你不知道你的写文将最终存在于文件中。

完全不清楚你要做什么。通常,您要编写HTMLParser类的自定义子类,以收集实例属性中的数据。然后,您可以调用.feed(),然后从这些属性中收集您想要的任何内容。

您可能最好使用更简单的HTML API,例如BeautifulSoup,这不需要您创建解析器子类,并且在简单的HTML提取任务时更容易使用。