1. 程式人生 > >python3 爬蟲—爬取天氣預報多個城市七天資訊(三)

python3 爬蟲—爬取天氣預報多個城市七天資訊(三)

一、內容:

       利用BeautifulSoup抓取中國天氣網各個城市7天的 時間 天氣狀態 最高溫 最低溫 的相關資訊,並記錄儲存在本地csv表格檔案中。

爬取的頁面截圖:

html獲取資訊截圖:

二、原理:

     1.利用requests獲取請求 、BeautifulSoup抓取資料。

     2.通過readlines()讀取city.txt檔案的天氣介面來生成各城市的url

     3.通過第三方庫csv將抓取的到的資料寫入weather.csv表格

獲取URL:
#  獲取每個城市對應天氣的url
def get_url(city_name):
    url = 'http://www.weather.com.cn/weather/'
    with open('D:\py_project\weather\city.txt', 'r', encoding='UTF-8') as fs:
        lines = fs.readlines()
        for line in lines:
            if(city_name in line):
                code = line.split('=')[0].strip()
                return url + code + '.shtml'
    raise ValueError('invalid city name')

傳送URL GET請求,獲取response:

#  對網頁獲取get請求,得到的是response物件
def get_content(url, data=None):
    #  模擬瀏覽器訪問
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    #  超時,取隨機數是因為防止被網站認定為網路爬蟲
    timeout = random.choice(range(80, 180))
    while True:
        try:
            #  獲取請求資料
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))
        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))
        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))
        except http.client.BadStatusLine as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))

    return rep.text

抓取天氣資訊:

# 獲取html中我們所需要的欄位:
def get_data(html_text, city_name):
    #  final元組存放七天的資料
    final = []
    t = []
    t.append(city_name)
    final.append(t)
    bs = BeautifulSoup(html_text, "html.parser")  # 建立BeautifulSoup物件,解析器為:html.parser
    body1 = bs.body  # 獲取body部分

    #  print(body1)
    data = body1.find('div', {'id': '7d'})  # 找到id為7d的div
    ul = data.find('ul')  # 獲取ul部分
    li = ul.find_all('li')  # 獲取所有的li

    for day in li:   # 對每個li標籤中的內容進行遍歷
        # temp代存每日的資料
        temp = []
        #  新增日期
        data = day.find('h1').string   # 找到日期
        temp.append(data)  # 新增到temp中

        inf = day.find_all('p')  # 找到li中的所有p標籤
        #  新增天氣狀況
        temp.append(inf[0].string)  # 第一個p標籤中的內容(天氣狀況)加到temp中
        #  新增最高氣溫
        if inf[1].find('span') is None:
            temperature_highest = None  # 天氣當中可能沒有最高氣溫(傍晚)
        else:
            temperature_highest = inf[1].find('span').string  # 找到最高氣溫
            temperature_highest = temperature_highest.replace('℃', '')
        temp.append(temperature_highest)  # 將最高溫新增進去
        # 新增最低氣溫
        temperature_lowest = inf[1].find('i').string  # 找到最低溫
        temperature_lowest = temperature_lowest.replace('℃', '')  # 最低溫度後面有個℃,去掉這個符號
        temp.append(temperature_lowest)  # 將最低溫新增上去

        final.append(temp)  # 將temp 加到final中

    return final

儲存資訊到CSV中:

# 將抓取出來的資料寫入檔案
def write_data(city_name, data, file_name):
    with open(file_name, 'a', errors='ignore', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)
        print('%s 天氣已新增成功' % city_name)

三、完整程式碼:
import requests
import csv
import random
import time
import socket
import http.client
from bs4 import BeautifulSoup


#  獲取每個城市對應天氣的url
def get_url(city_name):
    url = 'http://www.weather.com.cn/weather/'
    with open('D:\py_project\weather\city.txt', 'r', encoding='UTF-8') as fs:
        lines = fs.readlines()
        for line in lines:
            if(city_name in line):
                code = line.split('=')[0].strip()
                return url + code + '.shtml'
    raise ValueError('invalid city name')


#  對網頁獲取get請求,得到的是response物件
def get_content(url, data=None):
    #  模擬瀏覽器訪問
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    #  超時,取隨機數是因為防止被網站認定為網路爬蟲
    timeout = random.choice(range(80, 180))
    while True:
        try:
            #  獲取請求資料
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))
        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))
        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))
        except http.client.BadStatusLine as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))

    return rep.text


# 獲取html中我們所需要的欄位:
def get_data(html_text, city_name):
    #  final元組存放七天的資料
    final = []
    t = []
    t.append(city_name)
    final.append(t)
    bs = BeautifulSoup(html_text, "html.parser")  # 建立BeautifulSoup物件,解析器為:html.parser
    body1 = bs.body  # 獲取body部分

    #  print(body1)
    data = body1.find('div', {'id': '7d'})  # 找到id為7d的div
    ul = data.find('ul')  # 獲取ul部分
    li = ul.find_all('li')  # 獲取所有的li

    for day in li:   # 對每個li標籤中的內容進行遍歷
        # temp代存每日的資料
        temp = []
        #  新增日期
        data = day.find('h1').string   # 找到日期
        temp.append(data)  # 新增到temp中

        inf = day.find_all('p')  # 找到li中的所有p標籤
        #  新增天氣狀況
        temp.append(inf[0].string)  # 第一個p標籤中的內容(天氣狀況)加到temp中
        #  新增最高氣溫
        if inf[1].find('span') is None:
            temperature_highest = None  # 天氣當中可能沒有最高氣溫(傍晚)
        else:
            temperature_highest = inf[1].find('span').string  # 找到最高氣溫
            temperature_highest = temperature_highest.replace('℃', '')
        temp.append(temperature_highest)  # 將最高溫新增進去
        # 新增最低氣溫
        temperature_lowest = inf[1].find('i').string  # 找到最低溫
        temperature_lowest = temperature_lowest.replace('℃', '')  # 最低溫度後面有個℃,去掉這個符號
        temp.append(temperature_lowest)  # 將最低溫新增上去

        final.append(temp)  # 將temp 加到final中

    return final


# 將抓取出來的資料寫入檔案
def write_data(city_name, data, file_name):
    with open(file_name, 'a', errors='ignore', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)
        print('%s 天氣已新增成功' % city_name)


if __name__ == '__main__':

    cities = input('請輸入城市名稱(一個或多個,以空格隔開): ').split(' ')
    for city in cities:
        url = get_url(city)  # 獲取城市天氣的url
        html = get_content(url)  # 獲取網頁html
        result = get_data(html, city)  # 爬去城市的資訊
        write_data(city, result, 'D:\py_project\weather\weather.csv')  # 將爬取得資訊填入表格檔案


四、執行結果: