python3的urllib2报错问题解决方法

python
urlib2
兼容问题

在python3中,将urllib和urllib2合并了,所以在使用urllib2的地方改成urllib.request即可。
示例如下

  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获取城市的天气。

posted @ 2017-03-26 11:26  marsggbo  阅读(8732)  评论(0编辑  收藏  举报