开发者

Python 3.1 code and error

64-bit VISTA

Python 3.1

from urllib import request
a = request.urlopen('http://www.marketwatch.com/investing/currency/CUR_USDYEN').read(20500)
b = a[19000:20500]
idx_pricewrap = b.find('pricewrap')
context = b[idx_pricewrap:idx_pricewrap+80]
idx_bgLast = context.find('bgLast')
rate = context[idx_bgLast+8:idx_bgLast+15]
print(rate)
Traceback (开发者_运维知识库most recent call last):
 File "c:\P31Working\test_urllib.py", line 4, in 
   idx_pricewrap = b.find('pricewrap')
TypeError: expected an object with the buffer interface
Process terminated with an exit code of 1

I have NO idea what that error means.

Please help.


Python 3 is a lot more strict when it comes to the difference between bytes and (Unicode) strings. The result of urlopen(...).read(...) is of course an object of type bytes, and the implementation of bytes.find doesn't allow you to search for Unicode strings. In your case, you can simply replace "pricewrap" by a binary string:

idx_pricewrap = b.find(b'pricewrap')

Same applies to other .find calls. Python 2 encoded Unicode strings automatically where it made (less or more) sense, but Python 3 has introduced more restrictions that you need to be aware of.


I finally find a relevant example in the docs:

http://docs.python.org/py3k/library/urllib.request.html?highlight=urllib#examples

The first example gave me some understanding and led me to revising my code to

http://tutoree7.pastebin.com/sUq8s4wh

which works like a charm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜