pythonエラー問題解決
1974 ワード
天気情報の取得
よくある質問:
1. TypeError: can't use a string pattern on a bytes-like object
解決:python 3のurllib.readはbytesオブジェクトを返しますstringではありませんstringオブジェクトに変換しbytesを使用します.decodeメソッド
#encoding:UTF-8
import urllib.request
import re
def getHtml(url):
page=urllib.request.urlopen(url)
html=page.read()
page.close()
return html.decode('UTF-8')
def getWeather(html):
reg='<a href=(.*?)>*</a>'
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
解決:python 3のurllib.readはbytesオブジェクトを返しますstringではありませんstringオブジェクトに変換しbytesを使用します.decodeメソッド