Python爬蟲入門實戰--------一週天氣預報爬取
最近學校剛開始開設爬蟲課,我也剛剛如入門,嘗試寫了一個爬去成都市的一週的天氣預報。
目錄
一、軟體和庫的準備:
-
python環境安裝配置:安裝python所需要的環境(此處就不詳細的進行說明了,百度查詢),最好是使用python3.x版本,雖然現在大部分公司的專案都還是在使用2.x版本,但是3.x才是目前主流的,以後的專案肯定使用3.x居多。
-
編輯器:選擇一個合適的編輯器,python有許多編輯器,但是題主推薦使用pycharm和jupyter,具體安裝過程這裡就不再進行說明,安裝jupyter使用Anaconda一體式安裝要方便快捷一點。
-
需要使用到的庫:這裡我們要使用的庫主要有urllib.request、csv以及BeautifulSoup
- urllib庫:這個安裝python自帶的庫,也可以使用第三方更加方便強大的庫requests,這個庫需要自己去手動安裝,在cmd裡面使用pip install requests安裝就好了
- csv庫:屬於安裝pytohn環境自帶的庫,不需要再去手動安裝
- BeautifulSoup庫:這個庫需要手動安裝,BeautifulSoup是一個網頁解析庫,它支援很多解析器,不過最主流的有兩個。一個是python標準庫,一個是lxml HTML 解析器。兩者的使用方法相似:
from
bs4
import
BeautifulSoup
# Python的標準庫
BeautifulSoup(html,
'html.parser'
)
# lxml
BeautifulSoup(html,
'lxml'
)
- 使用pip安裝 pip install beautifulsoup安裝,如果出現這種問題:
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(int "Unit tests have failed!")?
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\17933\AppData\Local\Temp\pip-install-n7hwndyc\beautifulsoup\
是因為是python3.6對beautifulsoup4支援不夠好
就需要使用pip install --upgrade --force-reinstall beautifulsoup4安裝;
如果是使用的Anaconda安裝就方便多了,直接在環境裡面點選安裝就好了
二、爬蟲的編寫:
- 相關包的匯入:
import csv import urllib.request from bs4 import BeautifulSoup ## 引入解析模組BS4
- 模擬瀏覽器得到資料
url = "http://www.weather.com.cn/weather/101270101.shtml" header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36") # 設定頭部資訊 opener = urllib.request.build_opener() # 修改頭部資訊 opener.addheaders = [header] #修改頭部資訊 request = urllib.request.Request(url) # 製作請求 response = urllib.request.urlopen(request) # 得到請求的應答包 html = response.read() #將應答包裡面的內容讀取出來 html = html.decode('utf-8') # 使用utf-8進行編碼,不重新編碼就會成亂碼
- 查詢要爬取的部分
我們在頁面上找到我們所需要的資訊部分 ,我們需要日期、天氣以及溫度
找到對應的程式碼部分
全圖如下:
# 以上部分的程式碼如下:
final = [] #初始化一個空的list,我們為將最終的的資料儲存到list
bs = BeautifulSoup(html,"html.parser") # 建立BeautifulSoup物件
body = bs.body # 獲取body部分
data = body.find('div',{'id':'7d'}) # 找到id為7d的div
之後我們再往下看,我們所需要的資訊都存在ul標籤中,我們需要查詢ul標籤
ul = data.find('ul') # 獲取ul部分,由於ul標籤只有一個 我們使用find()函式,如果有多個我們使用find_all()
所需要的資訊在ul標籤裡面的li標籤內部,而且不止一個,所以我們需要使用find_all()方法
li = ul.find_all('li') # 獲取所有的li 返回的是list物件
4.對查詢到部分進行資料的爬取
我們最後將所有的資料儲存在list之中在進行寫入檔案
日期在li標籤的h1標籤之中
天氣在li標籤的第一個p標籤之中
溫度在第二個p標籤之中的span標籤之中
i = 0
for day in li: # 對每個li標籤中的內容進行遍歷
if i < 7:
temp = []
date = day.find('h1').string # 找到日期
# print (date)
temp.append(date) # 新增到temp中
# print (temp)
inf = day.find_all('p') # 找到li中的所有p標籤
# print(inf)
# print (inf[0])
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.append(temperature_lowest)
final.append(temp) # 將每一次迴圈的list的內容都插入最後儲存資料的list
i = i +1
5.寫入檔案:
with open('weather.csv', 'a', errors='ignore', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerows(final)
三、全部程式碼
import csv
import urllib.request
from bs4 import BeautifulSoup
url = "http://www.weather.com.cn/weather/101270101.shtml"
header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36") # 設定頭部資訊
opener = urllib.request.build_opener() # 修改頭部資訊
opener.addheaders = [header] #修改頭部資訊
request = urllib.request.Request(url) # 製作請求
response = urllib.request.urlopen(request) # 得到請求的應答包
html = response.read() #將應答包裡面的內容讀取出來
html = html.decode('utf-8') # 使用utf-8進行編碼,不重新編碼就會成亂碼
final = [] #初始化一個空的list,我們為將最終的的資料儲存到list
bs = BeautifulSoup(html,"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
# print (li)
i = 0
for day in li: # 對每個li標籤中的內容進行遍歷
if i < 7:
temp = []
date = day.find('h1').string # 找到日期
# print (date)
temp.append(date) # 新增到temp中
# print (temp)
inf = day.find_all('p') # 找到li中的所有p標籤
# print(inf)
# print (inf[0])
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.append(temperature_lowest)
final.append(temp)
i = i +1
# print(final)
with open('weather.csv', 'a', errors='ignore', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerows(final)
四、感受
爬蟲大致分為四步:
1.寫好模擬瀏覽器請求頭
2.明確你要爬取那些資料
3.將資料爬取下來並儲存(這是最難的一步)
4.將資料儲存到檔案
大家對我的文章如有什麼見解,請留言,我們一起進步。
如果此文章對你有所幫助那就是我最大的榮幸,請為我留下一個贊,算是隨我莫大的鼓勵。