UnicodeDecodeError: 'utf8' 编码无法解码位置34的字节0xc3: 数据结束意外

15 投票
4 回答
92851 浏览
提问于 2025-04-18 08:20

我正在尝试写一个抓取工具,但是在编码方面遇到了一些问题。当我试图把我想要的字符串复制到我的文本文件时,python2.7告诉我它无法识别编码,尽管里面没有特殊字符。我不知道这是否有用。

我的代码是这样的:

from urllib import FancyURLopener
import os

class MyOpener(FancyURLopener): #spoofs a real browser on Window
   version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

print "What is the webaddress?"
webaddress = raw_input("8::>")

print "Folder Name?"
foldername = raw_input("8::>")

if not os.path.exists(foldername):
    os.makedirs(foldername)

def urlpuller(start, page):
   while page[start]!= '"':
      start += 1
   close = start
   while page[close]!='"':
      close += 1
   return page[start:close]

myopener = MyOpener()

response = myopener.open(webaddress)
site = response.read()

nexturl = ''
counter = 0

while(nexturl!=webaddress):
   counter += 1
   start = 0
   
   for i in range(len(site)-35):
       if site[i:i+35].decode('utf-8') == u'<img id="imgSized" class="slideImg"':
         start = i + 40
         break
   else:
      print "Something's broken, chief. Error = 1"
   
   next = 0
   
   for i in range(start, 8, -1):
      if site[i:i+8] == u'<a href=':
         next = i
         break
   else:
      print "Something's broken, chief. Error = 2"
   
   nexturl = urlpuller(next, site)
   
   myopener.retrieve(urlpuller(start,site),foldername+'/'+foldername+str(counter)+'.jpg')

print("Retrieval of "+foldername+" completed.")

当我尝试在我使用的网站上运行它时,出现了这个错误:

Traceback (most recent call last):
  File "yada/yadayada/Python/scraper.py", line 37, in <module>
    if site[i:i+35].decode('utf-8') == u'<img id="imgSized" class="slideImg"':
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 34: unexpected end of data

当我把它指向http://google.com时,它运行得很好。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

但是当我尝试用utf-8解码时,如你所见,它并不奏效。

有什么建议吗?

4 个回答

0

与其使用你的for循环,不如试试下面这样的写法:

start = site.decode('utf-8').find('<img id="imgSized" class="slideImg"') + 40
1

这段代码是用来处理一些特定的任务的。它可能涉及到一些编程的基本概念,比如变量、循环和条件判断。简单来说,代码的作用就是根据给定的条件来执行不同的操作。

在编程中,我们通常会使用“如果...那么...”的逻辑来决定程序的行为。比如,如果某个条件成立,就执行某个动作;如果不成立,就执行另一个动作。这种方式帮助我们让程序更灵活。

此外,代码中可能会有一些重复的操作,这时候我们就会用到循环。循环可以让我们在满足特定条件的情况下,重复执行某段代码,直到条件不再满足为止。

总之,这段代码的目的是为了让计算机根据我们设定的规则来完成某些任务。理解这些基本概念后,你就能更好地掌握编程的技巧了。

site[i:i+35].decode('utf-8', errors='ignore')
3

在Sublime中打开csv文件,然后选择“另存为编码” -> UTF-8。

16
site[i:i+35].decode('utf-8')

你不能随便把收到的字节分开,然后让UTF-8来解码。UTF-8是一种多字节编码,这意味着一个字符可能需要1到6个字节来表示。如果你把它一分为二,然后让Python来解码,它会给你报错,提示unexpected end of data(数据意外结束)。

可以找一些现成的工具来帮你处理这些问题。比如BeautifulSoup或者lxml都是不错的选择。

撰写回答