requests+sqllite+BeautifulSoup爬取中国天气网

项目

目的:利用requests+sqllite+BeautifulSoup几种主要技术爬取中国天气网指定城市的7天天气数据
分析:可以查看这篇最后的小项目
在这里插入图片描述

sqllite部分

1.建数据库

sqllite数据库不用单独创建,在连接的时候有就连接,没有就自动创建。

conn = sqlite3.connect("weather.db")
2.建表
    def openDB(self):
        self.conn = sqlite3.connect("weather.db")
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute("create table weathers (wCity varchar(16),wDate varchar(16),wWeather varchar(64),wTemp varchar(32),constraint pk_weather primary key(wCity,wDate))")
        except:
            self.cursor.execute("delete from weathers")
3.往表里面插入爬取的数据
    def insert(self,city,ddate,weather,temp):
        try:
            self.cursor.execute("insert into weathers(wCity, wDate , wWeather, wTemp) values (?, ?, ?, ?)",(city, ddate, weather, temp))
        except Exception as err:
            print(err)
4.查询表里的数据做展示
    def showInfo(self):
        self.cursor.execute("select * from weathers")
        rows = self.cursor.fetchall()
        print("%-16s%-16s%-32s%-16s"%("city", "ddate", "weather", "temp"))
        for row in rows:
            print("%-16s%-16s%-32s%-16s"%(row[0], row[1], row[2], row[3]))
5.关闭数据库
    def closeDB(self):
        self.conn.commit()
        self.conn.close()

requests部分

1.分析url

兰州七天的网址:
兰州的
上海七天的网址:
上海
很明显,只有一串数字不同,好像这一串数字和不同地区是对应的,可以用字典来做映射

cityUrl = {'兰州':'101160101', '上海':'101020100'}
allUrl = "http://www.weather.com.cn/weather/"+cityUrl[city]+".shtml"
2.找表头

NetWork下面,ALL,然后刷新以下网页,把加载的包随便点开以下就可以看到很多信息
在这里插入图片描述

在这里插入图片描述

3.爬取

爬取完数据之后顺便调用insert插入数据库 requests知识点击查看

response = requests.get(url=allUrl,headers = self.headers)
4.转换编码格式
response.encoding="utf-8"
5.查看网页数据
html =  response.text
print(html)

BeautifulSoup部分

1.解析数据

第一个参数是字符串,第二个参数是解析器,html.parser是python自带的,第三方的用的多的是lxml等,lxml 查看

soup = BeautifulSoup(html, "html.parser")
2.利用css选取数据

在这里插入图片描述

除了css获取网页具体数据外还有xpath和BeautifulSoup对象的find和find_all方法。
xpath 查看

BeautifulSoup详解
得注意抛出异常

lis = soup.select("ul[class='t clearfix'] li")
            for li in lis:
                try:
                    date = li.select('h1')[0].text
                    weather = li.select('p[class="wea"]')[0].text
                    temp = li.select('p[class="tem"] span')[0].text + "/" + li.select('p[class="tem"] i')[0].text
                    print(city,date, weather, temp)
                    self.db.insert(city, date,weather, temp)
                except Exception as err:
                    print(err)

代码封装

###获取兰州,上海等城市的天气预报数据并保存到sqllite数据库weather.db数据库中,存储的表是weathers
"""
sql:"create table weathers (wCity varchar(16),wDate varchar(16),wWeather varchar(64),wTemp varchar(32),constraint pk_weather primary key(wCity,wDate))"

"""

from bs4 import BeautifulSoup,UnicodeDammit
import requests
import sqlite3

class CreateDB:
    def openDB(self):
        self.conn = sqlite3.connect("weather.db")
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute("create table weathers (wCity varchar(16),wDate varchar(16),wWeather varchar(64),wTemp varchar(32),constraint pk_weather primary key(wCity,wDate))")
        except:
            self.cursor.execute("delete from weathers")
    def closeDB(self):
        self.conn.commit()
        self.conn.close()

    def insert(self,city,ddate,weather,temp):
        try:
            self.cursor.execute("insert into weathers(wCity, wDate , wWeather, wTemp) values (?, ?, ?, ?)",(city, ddate, weather, temp))
        except Exception as err:
            print(err)

    def showInfo(self):
        self.cursor.execute("select * from weathers")
        rows = self.cursor.fetchall()
        print("%-16s%-16s%-32s%-16s"%("city", "ddate", "weather", "temp"))
        for row in rows:
            print("%-16s%-16s%-32s%-16s"%(row[0], row[1], row[2], row[3]))

class WeatherSpider:
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) \
            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Mobile Safari/537.36'
        }
        self.cityUrl = {'兰州':'101160101', '上海':'101020100'}
    def spider(self, city):
        if city not in self.cityUrl.keys():
            print(city+"不存在")
            return
        allUrl = "http://www.weather.com.cn/weather/"+self.cityUrl[city]+".shtml"
        print(allUrl)
        try:
            response = requests.get(url=allUrl,headers = self.headers)
            response.encoding="utf-8"
            html =  response.text
            soup = BeautifulSoup(html, "html.parser")
            lis = soup.select("ul[class='t clearfix'] li")
            for li in lis:
                try:
                    date = li.select('h1')[0].text
                    weather = li.select('p[class="wea"]')[0].text
                    temp = li.select('p[class="tem"] span')[0].text + "/" + li.select('p[class="tem"] i')[0].text
                    print(city,date, weather, temp)
                    self.db.insert(city, date,weather, temp)
                except Exception as err:
                    print(err)
        except Exception as err:
            print(err)

    def process(self, cities):
        self.db = CreateDB()
        self.db.openDB()
        for city in cities:
            self.spider(city)

        self.db.showInfo()
        self.db.closeDB()
ws = WeatherSpider()
ws.process(['兰州', '上海'])

结果:

》》》》》》》》
http://www.weather.com.cn/weather/101160101.shtml
list index out of range
兰州 25日(明天) 阴转多云 15/6℃
兰州 26日(后天) 晴 19/8℃
兰州 27日(周二) 多云 18/6℃
兰州 28日(周三) 多云转晴 19/7℃
兰州 29日(周四) 晴 21/7℃
兰州 30日(周五) 晴转多云 30/12℃
http://www.weather.com.cn/weather/101020100.shtml
list index out of range
上海 25日(明天) 多云 22/16℃
上海 26日(后天) 晴转阴 22/17℃
上海 27日(周二) 小雨转多云 21/18℃
上海 28日(周三) 阴 23/18℃
上海 29日(周四) 晴转多云 24/16℃
上海 30日(周五) 晴 27/18℃
city            ddate           weather                         temp            
兰州              25日(明天)         阴转多云                            15/6℃          
兰州              26日(后天)         晴                               19/8℃          
兰州              27日(周二)         多云                              18/6℃          
兰州              28日(周三)         多云转晴                            19/7℃          
兰州              29日(周四)         晴                               21/7℃          
兰州              30日(周五)         晴转多云                            30/12℃         
上海              25日(明天)         多云                              22/16℃         
上海              26日(后天)         晴转阴                             22/17℃         
上海              27日(周二)         小雨转多云                           21/18℃         
上海              28日(周三)         阴                               23/18℃         
上海              29日(周四)         晴转多云                            24/16℃         
上海              30日(周五)         晴                               27/18℃         

Process finished with exit code 0
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值