python3的urllib2报错问题解决方法

python
urlib2
兼容问题

在python3中,将urllib和urllib2合并了,因此在使用urllib2的地方改为urllib.request便可。
示例以下python

  1. import urllib2.request 
  2. url = 'http://apis.baidu.com/heweather/weather/free?city=beijing' 
  3. req = urllib.request.Request(url) 
  4. req.add_header("apikey","33481140591d83456d6486e55fb00686"
  5. resp = urllib.request.urlopen(req) 
  6. content = resp.read() 
  7. if(content): 
  8. print(content) 
  9.  
  10.  

改例是在经过百度提供的api获取城市的天气。web

相关文章
相关标签/搜索