[Tutor] Need help with converting script using 2.6's urllib2 to Python 3.1

Sander Sweers sander.sweers at gmail.com
Mon Oct 25 17:38:12 CEST 2010


On 25 October 2010 14:46, Richard D. Moores <rdmoores at gmail.com> wrote:
> I'd like to convert the script to 3.1, but I can't understand the docs
> for the 3.1 urllib module. Please someone tell me what to do.
> (Converting   'print rate'   to   'print(rate)'   I understand.)

Have you actually tried reading the documentation? The _very_ first
section of the urllib documentation we have urllib.request.urlopen
[1]. Which looks to me what you are looking for as a replacement to
urllib2.urlopen().

Some *untested* inline comments below.

> import urllib2
from urllib import request
> a = urllib2.urlopen('http://www.marketwatch.com/investing/currency/CUR_USDYEN').read(20500)
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
print(rate)

Also http://docs.python.org/library/2to3.html discusses the automated
tool for converting python code.

Greets
Sander

[1] http://docs.python.org/py3k/library/urllib.request.html#urllib.request.urlopen


More information about the Tutor mailing list