这是一段抓取天气预报的脚本,参考sanniandegudan的,我主要是用来练习Python下怎么对Mysql语句进行操作。

import urllib
import re
import MySQLdb

def get_weather(city = '上海'):
    # Request For The Web Page
    params = urllib.urlencode({'city':city})
    webpage = urllib.urlopen('http://weather.news.sohu.com/city_inc.php?%s' % params)
    webdata = webpage.read().replace('\n', '')

    # Match The Useful Information
    pattern = re.compile('<td class=blu01>([^<]*)<br>([^<]*)<br>([^<]*)<br>([^<]*)')
    db=MySQLdb.connect(host='localhost',      #连接数据库
                      user='test',
                      passwd='test',
                      db='mytable',
                      charset='gb2312')        #设置字符编码

    cursor=db.cursor()

    cursor.execute ("DROP TABLE IF EXISTS message")
    cursor.execute ("""
        CREATE TABLE message
            (
              riqi CHAR(40),
              tianqi CHAR(40),
              wendu CHAR(40),         
              fengli CHAR(40),
              jiangshuilv CHAR(40)
            )
      """)
       
    x = 0
    for weather in pattern.findall(webdata):     
        if x == 0:
            riqi='今天'
        elif x == 1:
            riqi='明天'
        else:
            riqi='后天'
        for i in range(4):
            print weather[i].strip()
        tianqi=weather[0]
        wendu=weather[1]
        fengli=weather[2]
        jiangshuilv=weather[3]
        sss="INSERT INTO message VALUES('%s','%s','%s','%s','%s')"%(riqi,tianqi,wendu,fengli,jiangshuilv)
        cursor.execute(sss)
        db.commit()
        x += 1
    cursor.close()
    db.close()

if __name__ == "__main__":
    get_weather()