|
python爬蟲之天氣預報網(wǎng)站--查看最近(15天)的天氣信息(正則表達式) 思路: 1.首先找到一個自己想要查看天氣預報的網(wǎng)站,選擇自己想查看的地方,查看天氣(例:http://www.tianqi.com/xixian1/15/) 2.打開'網(wǎng)頁源代碼',分析自己想要獲取數(shù)據(jù)的特點 3.運用正則表達式來對數(shù)據(jù)進行處理,獲得自己想要的數(shù)據(jù) #網(wǎng)站可能反爬蟲,需要繞過,這里用瀏覽器的代理(python默認的用戶代理是自己,需要改成瀏覽器的用戶代理,這樣就能繞過一些網(wǎng)站簡單的反爬蟲) 4.獲得數(shù)據(jù)后,對數(shù)據(jù)進行簡單的美化 5.把數(shù)據(jù)寫入文件(用pickle模塊)
2.打開'網(wǎng)頁源代碼',分析自己想要獲取數(shù)據(jù)的特點(不同網(wǎng)站的數(shù)據(jù)不同,需要具體問題具體分析)
3.1被網(wǎng)站禁止爬蟲效果圖如下:
3.2運用正則表達式來對數(shù)據(jù)進行處理,獲得自己想要的數(shù)據(jù) 代碼如下: 查看天氣預報import re import requestsfrom prettytable import PrettyTableurl='http://www.tianqi.com/xixian1/15/'#繞過網(wǎng)站反爬蟲txt=requests.get(url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36','Host':'www.tianqi.com'}).text#print(txt)s1=re.compile(r'<b>(\d\d月\d\d日)</b>') #日期print(s1.findall(txt))s2=re.compile(r'<li class='temp'>(.+) (-?\d+)(\W+)<b>(-?\d+)</b>℃</li>')print(s2.findall(txt)) s3=re.compile('>(.{1,4})</b></li>')print(s3.findall(txt))s4=re.compile(r'<li>([\u4e00-\u9fa5].+)</li>')print(s4.findall(txt))tianqi=[]for i in range(len(s1.findall(txt))): tianqi.append([s1.findall(txt)[i],s2.findall(txt)[i][0],s2.findall(txt)[i][1]+s2.findall(txt)[i][2]+s2.findall(txt)[i][3],s3.findall(txt)[i],s4.findall(txt)[i]])print(tianqi)ptable=PrettyTable('日期 天氣 氣溫(℃) 空氣質(zhì)量 風級'.split())for i in tianqi: ptable.add_row(i)print(ptable) 運行效果如下:
5.把數(shù)據(jù)寫入文件(pickle) 代碼如下: import re import requestsimport picklefrom prettytable import PrettyTableurl='http://www.tianqi.com/xixian1/15/'#繞過網(wǎng)站反爬蟲#把內(nèi)容寫入到文件中(序列化)try: with open('tianqi.txt','rb') as f: txt=pickle.load(f) print('結(jié)果已加載')except: txt=requests.get(url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36','Host':'www.tianqi.com'}).text with open('tianqi.txt','wb') as f: pickle.dump(txt,f) print('文件已寫入!')#print(txt)s1=re.compile(r'<b>(\d\d月\d\d日)</b>') #日期print(s1.findall(txt))s2=re.compile(r'<li class='temp'>(.+) (-?\d+)(\W+)<b>(-?\d+)</b>℃</li>')print(s2.findall(txt)) s3=re.compile('>(.{1,4})</b></li>')print(s3.findall(txt))s4=re.compile(r'<li>([\u4e00-\u9fa5].+)</li>')print(s4.findall(txt))tianqi=[]for i in range(len(s1.findall(txt))): tianqi.append([s1.findall(txt)[i],s2.findall(txt)[i][0],s2.findall(txt)[i][1]+s2.findall(txt)[i][2]+s2.findall(txt)[i][3],s3.findall(txt)[i],s4.findall(txt)[i]])print(tianqi)ptable=PrettyTable('日期 天氣 氣溫(℃) 空氣質(zhì)量 風級'.split())for i in tianqi: ptable.add_row(i)print(ptable) |
|
|