Python AttributeError: 模块“urllib”没有属性“urlopen”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39975367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AttributeError: module 'urllib' has no attribute 'urlopen'
提问by Himakar Reddy
I just started learning Python. I am sure i wrote the code right.
我刚开始学习 Python。我确定我写的代码是正确的。
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.
我也试过 `urllib.request 。我收到这个错误。
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
回答by lycuid
That does work for py2, but not for Python 3x. For Python 3x, urlopen
is present in urllib.request
:
这确实适用于 py2,但不适用于 Python 3x。对于 Python 3x,urlopen
存在于urllib.request
:
import urllib.request
urllib.request.urlopen(...)