在网页爬虫时,当出现上述问题,原因是一些控制字符(unicode)的问题,因此需要删除控制字符,如下:
def remove_control_characters(html):
def str_to_int(s, default, base=10):
if int(s, base) < 0x10000:
return chr(int(s, base))
return default
html = re.sub(u"&#(\d+);?", lambda c: str_to_int(c.group(1), c.group(0)), html)
html = re.sub(u"&#[xX]([0-9a-fA-F]+);?", lambda c: str_to_int(c.group(1), c.group(0), base=16), html)
html = re.sub(u"[\x00-\x08\x0b\x0e-\x1f\x7f]", "", html)
return html