1. 程式人生 > >python爬蟲"Hello World"級入門例項(二),使用json從中國天氣網抓取資料

python爬蟲"Hello World"級入門例項(二),使用json從中國天氣網抓取資料

一、二話不說先上程式碼

python2.7版

#!/usr/bin/python2.7
#-*- coding=UTF-8 -*-

import urllib
import json

def get_dic(url):
    page = urllib.urlopen(url)
    html = page.read()
    page.close()
    dic=json.loads(html)
    return dic

dic = get_dic("http://www.weather.com.cn/data/cityinfo/101010100.html")

print dic['weatherinfo'
]['city'] print dic['weatherinfo']['ptime'] print dic['weatherinfo']['temp1'] print dic['weatherinfo']['temp2'] print dic['weatherinfo']['weather']

python3.5版

#!/usr/bin/python3.5
#-*- coding=UTF-8 -*-

import urllib.request
import json

def get_dic(url):
    page = urllib.request.urlopen(url)
    html = page.read().decode('utf-8')
page.close() dic=json.loads(html) return dic dic = get_dic("http://www.weather.com.cn/data/cityinfo/101010100.html") print(dic['weatherinfo']['city']) print(dic['weatherinfo']['ptime']) print(dic['weatherinfo']['temp1']) print(dic['weatherinfo']['temp2']) print(dic['weatherinfo']['weather'])

看看效果
無描述

二、簡單說一下方法(以2.7版本程式碼為例)

def get_dic(url):
    page = urllib.urlopen(url)
    html = page.read()
    page.close()
    dic=json.loads(html)
    return dic

該函式通過urllib庫提供的urlopen和read函式獲取網頁中的資料,但是這個網頁的資料和一般的是有區別的,資料的格式是json的,所以後面就是重點,json.loads函式將返回的json格式資料解碼為python的字典格式。

好啦,到此為止,我們就通過該函式從網頁中獲得了一個包含了天氣資料的python字典,剩下的就是用字典的key來訪問字典中的資料了,是不是很簡單。

至於我們如何知道有哪些key呢,可以在訪問之前用

for key in dic['weatherinfo']:
    print key,dic['weatherinfo'][key]

來遍歷字典,看看有哪些內容,然後選選一些自己覺得需要的就好了。
還是附上原始碼下載連結吧
python2.7版
python3.5版