[파이썬 파충류] - 마지막 주 숙제.

2089 단어
# 
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']:
    # 
    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'
    }
    # 
    html = requests.get(url, headers=headers, timeout=3).content.decode('utf-8')
    # 
    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)
        # 
        write.writerow([h2['date'],h2['hmax'],h2['hmin'],h2['hgl']])

좋은 웹페이지 즐겨찾기