利用python3爬蟲爬取全國天氣數據並保存入Mysql數據庫

使用的python版本:3.6

導入的庫:

from bs4 import BeautifulSoup
import requests
import pymysql

首先開始觀察要爬取的網頁(此處爲中國天氣網天氣預報)

這是華北地區的天氣預報,可以觀察到網頁url爲:http://www.weather.com.cn/textFC/hb.shtml

 

那麼切換到東北地區

發現url只有textFC/後面的字符改變了,hb代表華北,db代表東北,所以由此可以建立一個url列表

 

urls = ['http://www.weather.com.cn/textFC/hb.shtml',
        'http://www.weather.com.cn/textFC/db.shtml',
        'http://www.weather.com.cn/textFC/hd.shtml',
        'http://www.weather.com.cn/textFC/hz.shtml',
        'http://www.weather.com.cn/textFC/hn.shtml',
        'http://www.weather.com.cn/textFC/xb.shtml',
        'http://www.weather.com.cn/textFC/xn.shtml']

只要循環遍歷此表,便可以獲取各個地區的天氣預報網頁url(由於港澳臺網頁結構較爲特殊,此處不做處理)

 

接下來定義一個get_temperature函數來查找網頁中需要的天氣信息

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}           # 設置頭文件信息
response = requests.get(url, headers=headers).content    # 提交requests get 請求
soup = BeautifulSoup(response, "lxml")       # 用Beautifulsoup 進行解析

構建一個headers參數,並提交request.get請求,接下來使用BeautifulSoup進行網頁的解析

在瀏覽器中按F12觀察網頁結構,可以發現頁面所有的城市信息及該城市的天氣信息都在<div class="conMidtab">的標籤下

 

而每個conMidtab2的標籤下的內容則爲該地區各個省的天氣信息

 

而該省不同城市的天氣信息還在conMidtab2的標籤下的table的標籤下的tbody裏的tr標籤內的td下,

而且還發現每個省的conMidtab2內的第3個tr標籤開始才爲真正的城市天氣信息,

而每個含有天氣信息的tr標籤的第一個td標籤裏含有省份信息,

分析完畢,開始編寫代碼

 

conmid = soup.find('div', class_='conMidtab')
conmid2 = conmid.findAll('div', class_='conMidtab2')

for info in conmid2:
    tr_list = info.find_all('tr')[2:]       # 使用切片取到第三個tr標籤
    for index, tr in enumerate(tr_list):     # enumerate可以返回元素的位置及內容
        td_list = tr.find_all('td')
        if index == 0:
            province_name = td_list[0].text.replace('\n', '')   # 取每個標籤的text信息,並使用replace()函數將換行符刪除
            city_name = td_list[1].text.replace('\n', '')
            weather = td_list[5].text.replace('\n', '')
            wind = td_list[6].text.replace('\n', '')
            max = td_list[4].text.replace('\n', '')
            min = td_list[7].text.replace('\n', '')
            print(province_name)
        else:
            city_name = td_list[0].text.replace('\n', '')
            weather = td_list[4].text.replace('\n', '')
            wind = td_list[5].text.replace('\n', '')
            max = td_list[3].text.replace('\n', '')
            min = td_list[6].text.replace('\n', '')

        print(city_name, weather, wind, max, min)

利用BeautifulSoup庫查找並輸出每個標籤的text天氣信息,再進行處理即爲想要的天氣信息,最後輸出。

完整代碼如下:

 

from bs4 import BeautifulSoup
import requests


def get_temperature(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}           # 設置頭文件信息
    response = requests.get(url, headers=headers).content    # 提交requests get 請求
    soup = BeautifulSoup(response, "lxml")       # 用Beautifulsoup 進行解析

    conmid = soup.find('div', class_='conMidtab')
    conmid2 = conmid.findAll('div', class_='conMidtab2')

    for info in conmid2:
        tr_list = info.find_all('tr')[2:]       # 使用切片取到第三個tr標籤
        for index, tr in enumerate(tr_list):     # enumerate可以返回元素的位置及內容
            td_list = tr.find_all('td')
            if index == 0:
                province_name = td_list[0].text.replace('\n', '')   # 取每個標籤的text信息,並使用replace()函數將換行符刪除
                city_name = td_list[1].text.replace('\n', '')
                weather = td_list[5].text.replace('\n', '')
                wind = td_list[6].text.replace('\n', '')
                max = td_list[4].text.replace('\n', '')
                min = td_list[7].text.replace('\n', '')
                print(province_name)
            else:
                city_name = td_list[0].text.replace('\n', '')
                weather = td_list[4].text.replace('\n', '')
                wind = td_list[5].text.replace('\n', '')
                max = td_list[3].text.replace('\n', '')
                min = td_list[6].text.replace('\n', '')

            print(city_name, weather, wind, max, min)


if __name__=='__main__':
    urls = ['http://www.weather.com.cn/textFC/hb.shtml',
            'http://www.weather.com.cn/textFC/db.shtml',
            'http://www.weather.com.cn/textFC/hd.shtml',
            'http://www.weather.com.cn/textFC/hz.shtml',
            'http://www.weather.com.cn/textFC/hn.shtml',
            'http://www.weather.com.cn/textFC/xb.shtml',
            'http://www.weather.com.cn/textFC/xn.shtml']
    for url in urls:
        get_temperature(url)

現在開始將爬取的信息利用pymysql保存入Mysql數據庫中

首先打開數據庫連接,並使用cursor()建立一個遊標對象

(在此之前你需要手動在數據庫中新建一個數據庫並新建一個表)

conn=pymysql.connect(host='localhost',user='你的用戶名',passwd='你的密碼',db='數據庫的名稱',port=3306,charset='utf8')
cursor=conn.cursor()

利用cursor,execute()函數將數據寫出你新建的表中

cursor.execute('insert into 你新建的表的名字(city,weather,wind,max,min) values(%s,%s,%s,%s,%s)',(city_name,weather,wind,max,min))

最後,使用commit( ) 將所寫的數據提交入數據庫即可

conn.commit()

最終完整代碼如下:

 

from bs4 import BeautifulSoup
import requests
import pymysql

conn=pymysql.connect(host='localhost',user='你的用戶名',passwd='你的密碼',db='你的數據庫名稱',port=3306,charset='utf8')
cursor=conn.cursor()
def get_temperature(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}           # 設置頭文件信息
    response = requests.get(url, headers=headers).content    # 提交requests get 請求
    soup = BeautifulSoup(response, "lxml")       # 用Beautifulsoup 進行解析

    conmid = soup.find('div', class_='conMidtab')
    conmid2 = conmid.findAll('div', class_='conMidtab2')

    for info in conmid2:
        tr_list = info.find_all('tr')[2:]       # 使用切片取到第三個tr標籤
        for index, tr in enumerate(tr_list):     # enumerate可以返回元素的位置及內容
            td_list = tr.find_all('td')
            if index == 0:
                province_name = td_list[0].text.replace('\n', '')   # 取每個標籤的text信息,並使用replace()函數將換行符刪除
                city_name = td_list[1].text.replace('\n', '')
                weather = td_list[5].text.replace('\n', '')
                wind = td_list[6].text.replace('\n', '')
                max = td_list[4].text.replace('\n', '')
                min = td_list[7].text.replace('\n', '')
                print(province_name)
            else:
                city_name = td_list[0].text.replace('\n', '')
                weather = td_list[4].text.replace('\n', '')
                wind = td_list[5].text.replace('\n', '')
                max = td_list[3].text.replace('\n', '')
                min = td_list[6].text.replace('\n', '')

            print(city_name, weather, wind, max, min)
            cursor.execute('insert into 你新建的表的名字(city,weather,wind,max,min) values(%s,%s,%s,%s,%s)',(city_name,weather,wind,max,min))




if __name__=='__main__':
    urls = ['http://www.weather.com.cn/textFC/hb.shtml',
            'http://www.weather.com.cn/textFC/db.shtml',
            'http://www.weather.com.cn/textFC/hd.shtml',
            'http://www.weather.com.cn/textFC/hz.shtml',
            'http://www.weather.com.cn/textFC/hn.shtml',
            'http://www.weather.com.cn/textFC/xb.shtml',
            'http://www.weather.com.cn/textFC/xn.shtml']
    for url in urls:
        get_temperature(url)
    conn.commit()

謝謝大家!

源代碼下載鏈接   https://download.csdn.net/download/u013523775/10589499

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章