Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: module 'urllib' has no attribute 'urlopen' [duplicate]

I just started learning Python. I am sure i wrote the code right.

import urllib
import re


stockname = input('Enter the stock name : ')

url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol="+stockname+"&illiquid=0&smeFlag=0&itpFlag=0"
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="lastPrice">'+stockname+'</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
print (price)

but i keep on getting this error no matter how much i try.

Enter the stock name : tcs
Traceback (most recent call last):
  File "C:\Users\.....\Desktop\stockq.py", line 8, in <module>
    htmlfile = urllib.urlopen(url)
AttributeError: module 'urllib' has no attribute 'urlopen'

I tried `urllib.request as well. I get this error.

Traceback (most recent call last):
  File "C:\Users\HiMMi\Desktop\stockq.py", line 8, in <module>
    htmlfile = urllib.request.urlopen(url)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Users\HiMMi\AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
like image 919
Himakar Reddy Avatar asked Nov 27 '22 05:11

Himakar Reddy


1 Answers

That does work for py2, but not for Python 3x. For Python 3x, urlopen is present in urllib.request:

import urllib.request

urllib.request.urlopen(...)
like image 62
lycuid Avatar answered Dec 06 '22 22:12

lycuid