Python 3.1 代码和错误
64位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
我不知道该错误意味着什么。
请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 3 对于字节和 (Unicode) 字符串之间的区别更加严格。
urlopen(...).read(...)
的结果当然是一个bytes
类型的对象,而bytes.find< 的实现/code> 不允许您搜索 Unicode 字符串。在您的情况下,您可以简单地用二进制字符串替换“pricewrap”:
这同样适用于其他
.find
调用。 Python 2 在有意义(或多或少)的地方自动编码 Unicode 字符串,但 Python 3 引入了更多您需要注意的限制。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 typebytes
, and the implementation ofbytes.find
doesn't allow you to search for Unicode strings. In your case, you can simply replace "pricewrap" by a binary string: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.我终于在文档中找到了相关示例:
http:// /docs.python.org/py3k/library/urllib.request.html?highlight=urllib#examples
第一个示例给了我一些理解,并引导我将代码修改为
http://tutoree7.pastebin.com/sUq8s4wh
效果就像一个魅力。
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.