首页 > 代码库 > python 错误问题解决

python 错误问题解决

获取天气信息

#encoding:UTF-8import urllib.requestimport redef getHtml(url):     page=urllib.request.urlopen(url)    html=page.read()        page.close()     return html.decode(UTF-8)def getWeather(html):     reg=<a href=http://www.mamicode.com/(.*?)>*    weatherList=re.compile(reg).findall(html)     return weatherList weatherList=getWeather(getHtml(http://gd.weather.com.cn/)) for weather in weatherList:     print (weather)  

常见问题:

1. TypeError: can‘t use a string pattern on a bytes-like object

   解决: python3中urllib.read返回的是bytes对象,  不是string,得把它转换成string对象,用bytes.decode方法

python 错误问题解决