爬蟲:抓取某年某月某日某地的天氣資訊
阿新 • • 發佈:2019-01-08
# -*- coding:utf-8 -*-
import urllib2
import os
# 抓取網頁內容,並存入臨時txt
def get_web_page(address1, date1):
url = 'http://' + address1 + '.tianqi.com/' + date1 + '.html'
page = urllib2.urlopen(url).read()
page_content = page[:7330].decode('GB2312').encode('utf-8')
f = open('temp.txt', 'w')
f.write(page_content)
f.close()
return
# 處理txt,返回結果,並刪除臨時txt
def deal_page():
f = open('temp.txt', 'r')
for i in range(6):
f.readline()
result = f.readline()
site = result.index(',') + 3
result = result[site:]
site = result[:-1].index('"')
f.close()
os.remove('temp.txt')
return result[:site]
if __name__ == '__main__':
address = input(u"請用拼音輸入您查詢的地點(如'luoyang')")
date = input(u"請輸入您查詢的日期(如'20170228'最早只能查詢到2012年4月1日)")
get_web_page(address, date)
print u'以下是您輸入條件的天氣情況,如有誤請在地點名稱後加1,再次查詢'
print deal_page()