python版本: 3.5
IDE : pycharm 5.0.4
要用到的包可以用pycharm下載:
File->Default Settings->Default Project->Project Interpreter
選擇python版本並點右邊的加號安裝想要的包
我選擇的網站是中國天氣網中的蘇州天氣,准備抓取最近7天的天氣以及最高/最低氣溫
http://www.weather.com.cn/weather/101190401.shtml
PS:如有需要最新Python入門到實戰學習資料的朋友可以點擊下方鏈接自行獲取
http://note.youdao.com/noteshare?id=a3a533247e4c084a72c9ae88c271e3d1
程序開頭我們添加:
# coding : UTF-8
- 1
- 2
這樣就能告訴解釋器該py程序是utf-8編碼的,源程序中可以有中文。
要引用的包:
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方便(我一開始用的是這一種)
獲取網頁中的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
timeout是設定的一個超時時間,取隨機數是因為防止被網站認定為網絡爬蟲。
然后通過requests.get方法獲取網頁的源代碼、
rep.encoding = ‘utf-8’是將源代碼的編碼格式改為utf-8(不該源代碼中中文部分會為亂碼)
下面是一些異常處理
返回 rep.text
獲取html中我們所需要的字段:
這里我們主要要用到BeautifulSoup
BeautifulSoup 文檔http://www.crummy.com/software/BeautifulSoup/bs4/doc/
首先還是用開發者工具查看網頁源碼,並找到所需字段的相應位置
找到我們需要字段都在 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步:
1、模擬瀏覽器訪問,獲取html源代碼
2、通過正則匹配,獲取指定標簽中的內容
3、將獲取到的內容寫到文件中
剛學python爬蟲,可能有些理解有錯誤的地方,請大家批評指正,謝謝!