本文實例為大家分享了python爬取哈爾濱天氣信息的具體代碼,供大家參考,具體內容如下
環境:
windows7
python3.4(pip install requests;pip install BeautifulSoup4)
代碼: (親測可以正確執行)
# coding:utf-8"""總結一下,從網頁上抓取內容大致分3步:1、模擬瀏覽器訪問,獲取html源代碼2、通過正則匹配,獲取指定標簽中的內容3、將獲取到的內容寫到文件中"""import requests # 用來抓取網頁的html源代碼import csv # 將數據寫入到csv文件中import random # 取隨機數import time # 時間相關操作import socket # 用于異常處理import http.client # 用于異常處理from bs4 import BeautifulSoup # 用來代替正則式取源碼中相應標簽中的內容# 獲取網頁中的html代碼def get_content(url, data=None): header = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } timeout = random.choice(range(80, 180)) # timeout是設定的一個超時時間,取隨機數是因為防止被網站認定為網絡爬蟲 while True: try: rep = requests.get(url, headers=header, timeout=timeout) rep.encoding = 'utf-8' # rep.encoding = ‘utf-8'是將源代碼的編碼格式改為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.IncompleteRead as e: print('6:', e) time.sleep(random.choice(range(5, 15))) return rep.text# 獲取html中我們所需要的字段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# 寫入文件csvdef 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)if __name__ == '__main__': url = 'http://www.weather.com.cn/weather/101050101.shtml' html = get_content(url) result = get_data(html) write_data(result, 'weather.csv')
新聞熱點
疑難解答