Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中

复制代码
测试链接:https://lishi.tianqi.com/guangzhou/202003.html

源码:

复制代码
import requests, pymysql
from lxml import etree
class ThSpider(object):
    def __init__(self):
        # 初始化
        self.month_list = ['202101', '202102', '202103', '202104', '202105', '202106', '202107', '202108', '202109', '202110', '202111', '202112', '202201', '202202']
        # 链接数据库
        self.cz = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='root',
            db='基本操作',
            charset='utf8'
        )
        # 创建游标
        self.kit = self.cz.cursor()
        # 创建数据库
        table_sql = \
            '''
                create table if not exists 天气数据 (
                    日期 varchar (50),
                    最高气温 varchar (50),
                    最低气温 varchar (50),
                    天气 varchar (50),
                    风向 varchar (50)
                );
            '''
        self.kit.execute(table_sql)

    def request_start_url(self):
        # 发送请求 + 得到响应
        for month in self.month_list:
            start_url = 'https://lishi.tianqi.com/shanghai/{}.html'.format(month)
            self.headers = {
                'Cookie': 'UserId=17209281674394559; Hm_lvt_7c50c7060f1f743bccf8c150a646e90a=1720928176; HMACCOUNT=66A8254591DC78E3; Hm_lpvt_7c50c7060f1f743bccf8c150a646e90a=1720941400',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
            }
            response = requests.get(start_url, headers=self.headers).text
            self.parse_response(response)
        self.commit_close()  # 也可在此处调用提交函数  请求一个月份,解析一个月份,然后提交数据库

    def parse_response(self, response):
        # 解析响应 + 得到字段
        A = etree.HTML(response)
        li_list = A.xpath('//ul[@class="thrui"]/li')
        for li in li_list:
            # 日期
            rq = li.xpath('./div[1]/text()')[0]
            # 最高气温
            gw = li.xpath('./div[2]/text()')[0]
            # 最低气温
            dw = li.xpath('./div[3]/text()')[0]
            # 天气
            tq = li.xpath('./div[4]/text()')[0]
            # 风向
            fx = li.xpath('./div[5]/text()')[0]
            # print(rq, gw, dw, tq, fx)
            insert_sql = \
                '''
                    insert into 天气数据 values ("{}", "{}", "{}", "{}", "{}")
                '''.format(rq, gw, dw, tq, fx)
            self.kit.execute(insert_sql)
            print('ok --{}'.format(rq))

    def commit_close(self):
        # 数据库的提交和关闭
        self.kit.close()
        self.cz.commit()
        self.cz.close()

    def main(self):
        self.request_start_url()
        # self.commit_close()

if __name__ == '__main__':
    th = ThSpider()
    th.main()

运行效果:

相关推荐
rgb2gray1 分钟前
AI 的“诚实”指南:一文详解 Conformal Prediction (共形预测) 与 Split Conformal
人工智能·python·机器学习·数据分析·可解释·共性预测·一致性预测
hakesashou3 分钟前
python 如何使数组中的元素不重复
开发语言·python
Filotimo_4 分钟前
JWT的概念
java·开发语言·python
刘大猫.6 分钟前
XNMS项目-mysql数据库同步
数据库·统计·同步·数据同步·数据统计·数据库同步·业务统计
Agilex松灵机器人14 分钟前
持续更新|从零到玩转Moveit机械臂控制(一)
人工智能·python·机器人·学习方法
喵手24 分钟前
《Python爬虫工程化实战》专栏导读|从“脚本能跑”到“系统能交付”:零基础也能做出可部署的 Python 爬虫!
爬虫·python·网络爬虫·爬虫实战·python爬虫·python爬虫工程化·爬虫实战教学
踢足球092926 分钟前
寒假打卡:2026-01-22
数据库·sql
数巨小码人30 分钟前
核心架构深度解析-揭开国产数据库内核的神秘面纱
数据库·架构
子午31 分钟前
【2026原创】卫星遥感图像识别系统+Python+深度学习+人工智能+算法模型+TensorFlow
人工智能·python·深度学习