我正在尝试编写一个 scraper ,但我遇到了编码问题。当我试图将要查找的字符串复制到我的文本文件中时,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 对其进行解码,它会抛出 unexpected end of data
错误。
查看为您构建的工具。 BeautifulSoup或 lxml有两种选择。
关于python - Unicode解码错误: 'utf8' codec can't decode byte 0xc3 in position 34: unexpected end of data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24004278/