1. 程式人生 > >python 查天氣學習筆記2(crossin的程式設計教室)

python 查天氣學習筆記2(crossin的程式設計教室)

  • 然而,照樣輸入程式會報錯:
  • provinces=content1.split(',')
  • TypeError: a bytes-like object is required, not 'str'
  • 於是,加了一句就OK啦,轉化為字串:content1=str(urllib.request.urlopen(url1).read(),encoding='utf-8')
  • 得到的是一個list
  • 同理抓取省份的城市,城市的地區資訊
  • import urllib.request
    
    result='city={\n'
    url1= 'http://m.weather.com.cn/data3/city.xml'
    content1 = urllib.request.urlopen(url1).read()# bytes #抓取省份資訊,獲得省份編號
    content1=str(urllib.request.urlopen(url1).read(),encoding='utf-8')
    provinces=content1.split(',')
    
    url = 'http://m.weather.com.cn/data3/city%s.xml'
    for p in provinces:#抓取城市資訊
       p_code = p.split('|')[0]
       url2 = url % p_code
       content2 = str(urllib.request.urlopen(url2).read(),encoding='utf-8')
       cities = content2.split(',')
       for c in cities:#抓取地區資訊
           c_code = c.split('|')[0]
           url3 = url % c_code #把字串中的%s 替換為c_code
           content3 = str(urllib.request.urlopen(url3).read(),encoding='utf-8')
           districts = content3.split(',')
           for d in districts:#獲得地區最終編號
               d_pair = d.split('|')
               d_code = d_pair[0]#編號
               name = d_pair[1]#地區名
               url4 = url % d_code
               content4 = str(urllib.request.urlopen(url4).read(),encoding='utf-8')
               code = content4.split('|')[1]
               line = "    '%s': '%s',\n" % (name, code)
               result += line
    
    result+='}'
    with open('getcity.py','w') as f:
        f.write(result)

    結果:海淀:101010200 朝陽:101010300 順義:101010400 懷柔:101010500 通州:101010600 昌平:101010700 延慶:101010800 豐臺:101010900等