Python 3.1 代码和错误

发布于 2024-09-28 20:11:29 字数 635 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

攒一口袋星星 2024-10-05 20:11:30

Python 3 对于字节和 (Unicode) 字符串之间的区别更加严格。 urlopen(...).read(...) 的结果当然是一个 bytes 类型的对象,而 bytes.find< 的实现/code> 不允许您搜索 Unicode 字符串。在您的情况下,您可以简单地用二进制字符串替换“pricewrap”:

idx_pricewrap = b.find(b'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 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.

烛影斜 2024-10-05 20:11:30

我终于在文档中找到了相关示例:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文