【Python爬蟲】--最后一周作業(yè)

#天氣預(yù)報(bào)
import requests
import json
import csv

f = open('JS.csv', 'a', newline='', encoding='gbk')
write = csv.writer(f)
# 寫入index
write.writerow(['日期', '高溫', '低溫', '相對濕度'])
for i in ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13']:
    #按月份循環(huán)
    url = 'http://d1.weather.com.cn/calendar_new/2017/101210101_2017%s.html?_=1502786294211' % i
    headers = {
        'Host': 'd1.weather.com.cn',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
        'Accept': '*/*',
        'Referer': 'http://www.weather.com.cn/weather40d/101210101.shtml',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Cookie': 'vjuids=d20d90710.15de4c794ac.0.6016dd9676ec9; BIGipServerd1src_pool=1874396221.20480.0000; UM_distinctid=15de4c795a0260-0e09ba56654c25-5c1b3517-1fa400-15de4c795a1407; __asc=9e20a3cb15de4f1b3c91a9f00b4; __auc=530e787715de4c7acf66d9b28f2; returnUrl=http%3A%2F%2Fwww.weather.com.cn%2Fprofile%2Fcity.shtml; f_city=%E6%9D%AD%E5%B7%9E%7C101210101%7C; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1502781872; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1502786257; vjlast=1502781871.1502781871.30'
    }
    #請求網(wǎng)頁內(nèi)容
    html = requests.get(url, headers=headers, timeout=3).content.decode('utf-8')
    #解析結(jié)果
    h1 = html.lstrip('var fc40 = [').split('},')
    #打開文件

    for i in h1:
        if i.endswith(']'):
            i = i.rstrip(']')
        elif not i.endswith('}'):
            i = i + '}'
        h2 = json.loads(i)
        #寫入日期內(nèi)容
        write.writerow([h2['date'],h2['hmax'],h2['hmin'],h2['hgl']])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容