天气数据抓取 python

天气数据抓取

from my wp blog

帮同学抓取天气信息

选择了一个不错的天气网

http://lishi.tianqi.com/beijing/index.html

lxml解析html

先找一个靠谱的html解析工具beautifulsoup

本来这货用起来还是挺方便的,不过我会一点xpath,所以需要一个更高级的第三方库lxml

import lxml.html
weather_url = 'http://lishi.tianqi.com/beijing/201404.html'
html = lxml.html.parse(weather_url)
ul = html.xpath('//*[@id="tool_site"]/div[2]/ul')

所需的数据

2014-04-01 2 29 多云 微风 小于3级

页面的ul是抓出来了,但是还有一些混杂的内容,要过滤掉没用的东西

ul的第一个li中有个a标签,a中的内容才是需要的,而其他li中直接就是所需的内容

def getLi(ul):
    info = []
    k = 0
    for li in ul.itertext():
        text = li if 0 != k else li[0]
        if(text.strip()):
            info.append(text)
        k += 1
    return info

已经知道,第一个数据是个日期,如果判断出第一个数据是日期,那么整条数据都是有效的

import re
date_re = re.compile(r'^\d+-\d+-\d+$')
li = getLi(ul)
if(date_re.match(li[0])):
    ...(写入数据库或者文件)

python2的字符串是这样的

     decode              encode
str ---------> unicode --------->str

当想在程序中显示中文的时候,要转换成unicode字符

当时想写入文件或者数据库的时候,要对unicode字符串进行编码

一般来说,抓取的我国网页用gbk解码,写入文件使用utf8编码

import re
date_re = re.compile(r'^\d+-\d+-\d+$')
file = open('data.txt', 'w')
for ul in html.xpath('//*[@id="tool_site"]/div[2]/ul'):
    li = getLi(ul)
    if(date_re.match(li[0])):
        for text in li:
            file.write(text.encode('utf8') + ' ')
        file.write('\n')

python连接mysql需要下载一个叫做MySQLdb的库

开启本地的apache和mysql服务,连接和关闭数据库

conn = MySQLdb.connect(host=setting.host, user=setting.user, passwd=setting.passwd, db=setting.db, port=setting.port, charset='utf8')
cursor = conn.cursor()
 
conn.commit()
cursor.close()
conn.close()

为什么有conn.commit(),其他的语言里面(至少是php)没有见过

因为这样才能真正把数据写入到数据库中,完成一个事务

  • 关于编码
    • utf-8
    • 数据库utf8-general-ci
    • charset=’utf8′
    • 连接数据库声明字符编码
    • 写入的字符串用utf8编码
cursor.execute(sql.encode('utf8'))
    原文作者:Amrzs
    原文地址: https://www.jianshu.com/p/5a20d7b78ff5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞