我的代码看起来像这样:
from urllib import FancyURLopenerimport osclass 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 = 0while(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" ': 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" ': 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进行解码时,正如您所看到的,它不起作用.
有什么建议?
解决方法site[i:i+35].decode('utf-8')
您不能随机对您收到的字节进行分区,然后请UTF-8对其进行解码. UTF-8是一种多字节编码,这意味着您可以使用1到6个字节来表示一个字符.如果你把它切成两半,并要求Python解码它,它会让你意外结束数据错误.
查看为您构建的工具. BeautifulSoup或lxml是两种选择.
总结以上是内存溢出为你收集整理的python – UnicodeDecodeError:’utf8’编解码器无法解码位置34的字节0xc3:意外的数据结束全部内容,希望文章能够帮你解决python – UnicodeDecodeError:’utf8’编解码器无法解码位置34的字节0xc3:意外的数据结束所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)