Python網絡爬蟲入門實戰(爬取最近7天的天氣以及最高/最低氣溫)

 

前言 本文文字及圖片來源於網絡,僅供學習、交流使用,不具備任何商業用途,版權歸原做者全部,若有問題請及時聯繫咱們以做處理。 做者:

python版本: 3.5 
IDE : pycharm 5.0.4 
要用到的包能夠用pycharm下載: 
File->Default Settings->Default Project->Project Interpreter 
選擇python版本並點右邊的加號安裝想要的包 
這裏寫圖片描述
html

我選擇的網站是中國天氣網中的蘇州天氣,準備抓取最近7天的天氣以及最高/最低氣溫 
http://www.weather.com.cn/weather/101190401.shtml 
這裏寫圖片描述python

程序開頭咱們添加:web

# coding : UTF-8 
  • 1
  • 2

這樣就能告訴解釋器該py程序是utf-8編碼的,源程序中能夠有中文。chrome

要引用的包:瀏覽器

import requests import csv import random import time import socket import http.client # import urllib.request from bs4 import BeautifulSoup
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

requests:用來抓取網頁的html源代碼 
csv:將數據寫入到csv文件中 
random:取隨機數 
time:時間相關操做 
socket和http.client 在這裏只用於異常處理 
BeautifulSoup:用來代替正則式取源碼中相應標籤中的內容 
urllib.request:另外一種抓取網頁的html源代碼的方法,可是沒requests方便(我一開始用的是這一種)markdown

獲取網頁中的html代碼:網絡

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' # req = urllib.request.Request(url, data, header) # response = urllib.request.urlopen(req, timeout=timeout) # html1 = response.read().decode('UTF-8', errors='ignore') # response.close() break # except urllib.request.HTTPError as e: # print( '1:', e) # time.sleep(random.choice(range(5, 10))) # # except urllib.request.URLError as e: # print( '2:', e) # time.sleep(random.choice(range(5, 10))) 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.IncompleteRead as e: print( '6:', e) time.sleep(random.choice(range(5, 15))) return rep.text # return html_text
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

header是requests.get的一個參數,目的是模擬瀏覽器訪問 
header 可使用chrome的開發者工具得到,具體方法以下: 
打開chrome,按F12,選擇network 
這裏寫圖片描述
從新訪問該網站,找到第一個網絡請求,查看它的header 
這裏寫圖片描述app

timeout是設定的一個超時時間,取隨機數是由於防止被網站認定爲網絡爬蟲。 
而後經過requests.get方法獲取網頁的源代碼、 
rep.encoding = ‘utf-8’是將源代碼的編碼格式改成utf-8(不應源代碼中中文部分會爲亂碼) 
下面是一些異常處理 
返回 rep.textpython爬蟲

獲取html中咱們所須要的字段: 
這裏咱們主要要用到BeautifulSoup 
BeautifulSoup 文檔http://www.crummy.com/software/BeautifulSoup/bs4/doc/dom

首先仍是用開發者工具查看網頁源碼,並找到所需字段的相應位置這裏寫圖片描述
找到咱們須要字段都在 id = 「7d」的「div」的ul中。日期在每一個li中h1 中,天氣情況在每一個li的第一個p標籤內,最高溫度和最低溫度在每一個li的span和i標籤中。 
感謝Joey_Ko指出的錯誤:到了傍晚,當天氣溫會沒有最高溫度,因此要多加一個判斷。 
代碼以下:

def get_data(html_text): final = [] bs = BeautifulSoup(html_text, "html.parser") # 建立BeautifulSoup對象 body = bs.body # 獲取body部分 data = body.find('div', {'id': '7d'}) # 找到id爲7d的div ul = data.find('ul') # 獲取ul部分 li = ul.find_all('li') # 獲取全部的li for day in li: # 對每一個li標籤中的內容進行遍歷 temp = [] date = day.find('h1').string # 找到日期 temp.append(date) # 添加到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('℃', '') # 到了晚上網站會變,最高溫度後面也有個℃ temperature_lowest = inf[1].find('i').string # 找到最低溫 temperature_lowest = temperature_lowest.replace('℃', '') # 最低溫度後面有個℃,去掉這個符號 temp.append(temperature_highest) # 將最高溫添加到temp中 temp.append(temperature_lowest) #將最低溫添加到temp中 final.append(temp) #將temp加到final中 return final
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

寫入文件csv: 
將數據抓取出來後咱們要將他們寫入文件,具體代碼以下:

def write_data(data, name): file_name = name with open(file_name, 'a', errors='ignore', newline='') as f: f_csv = csv.writer(f) f_csv.writerows(data)
  • 1
  • 2
  • 3
  • 4
  • 5

主函數:

if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101190401.shtml' html = get_content(url) result = get_data(html) write_data(result, 'weather.csv') 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

而後運行一下: 
生成的weather.csv文件以下: 
這裏寫圖片描述

總結一下,從網頁上抓取內容大體分3步: 
一、模擬瀏覽器訪問,獲取html源代碼 
二、經過正則匹配,獲取指定標籤中的內容 
三、將獲取到的內容寫到文件中

剛學python爬蟲,可能有些理解有錯誤的地方,請你們批評指正,謝謝!

相關文章
相關標籤/搜索