我正在尝试编写一个剪贴板,但我遇到编码问题.当我试图将我正在寻找的字符串复制到我的文本文件中时,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进行解码时,正如您所看到的,它不起作用.
有什么建议?
解决方法
site[i:i+35].decode('utf-8')
您不能随机对您收到的字节进行分区,然后请UTF-8对其进行解码. UTF-8是一种多字节编码,这意味着您可以使用1到6个字节来表示一个字符.如果你把它切成两半,并要求Python解码它,它会让你意外结束数据错误.
查看为您构建的工具. BeautifulSoup或lxml是两种选择.