Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python urllib usage

I imported two libraries urllib and from urllib.request import urlopen.

The second one is contained in the first

When I went over the code and tried to remove the from urllib.request import urlopen line , I got this message:

opnerHTMLnum = urllib.request.build_opener()
AttributeError: 'module' object has no attribute 'request'

When I restore the from urllib.request import urlopen line the code runs .

Can anyone explain why?

import re
#import http.cookiejar
import os.path
#import time
#import urllib3
import urllib
from urllib.request import urlopen
import sys
import smtplib
from email.mime.text import MIMEText

# ...

    opnerHTMLnum = urllib.request.build_opener()
like image 542
user1771754 Avatar asked Oct 24 '12 16:10

user1771754


2 Answers

The urllib package is just that, a package. It's __init__.py does not import urllib.request and thus you cannot simply reach urllib.request by only importing urllib. It is intended as a namespace only.

Import urllib.request instead.

like image 45
Martijn Pieters Avatar answered Sep 22 '22 19:09

Martijn Pieters


You are confusing python3 package urllib.request with Python2.7 one which is urllib2. Please don't do that. Python3 and Python2 are libraries are different. All you may want is urllib2 from python2

import urllib2
from urllib2 import Request
req = Request("yoururl")
res = urllib2.urlopen(req)
like image 147
Senthil Kumaran Avatar answered Sep 25 '22 19:09

Senthil Kumaran