(爬)康是美門市查詢並轉存csv

(爬)康是美門市查詢並轉存csv 

暨昨天爬7-11門市,今天練習爬康是美看看。

觀察網頁形態

首先一樣觀察一下網頁是怎樣運作的。

上圖可以看到第4個標號下,就是以json方式可以直接爬取資訊的
地方。
現在回到headers,驗證一下網址,連進去看看是不是我要的資訊

果然就是它了
https://www.cosmed.com.tw/api/getStore.aspx?t=store&c=%E8%87%BA%E5%8C%97%E5%B8%82&d=&s=

網址裡有一個c=,那裡可以打入其它地區看是否會順利連結到要爬
的地區,如果可以,在寫程式時就可使用input的方式自行輸入。

程式碼

import requests
import csv

while True:
    city=input("請輸入要查詢的門市: ")
    for i in city:
        url='https://www.cosmed.com.tw/api/getStore.aspx?t=store&c=%s&d=&s='%str(city)
        # url='https://www.cosmed.com.tw/api/getStore.aspx?t=store&c=花蓮縣&d=&s='
        html=requests.get(url).json()
        data=html['data']
    dataAll=[]
    for i,d in enumerate(data):
        storeName=d['StoreNM']
        ZipCodeName1=d['ZipCodeName1']
        ZipCodeName2=d['ZipCodeName2']
        add=d['Address']
        dataAll.append([storeName,ZipCodeName1,ZipCodeName2,add])

        print(i, storeName)
        print('{},{},{}'.format(ZipCodeName1,ZipCodeName2,add))
    with open('out.csv''a+', newline='',encoding='utf-8'as f:
        file=csv.writer(f)
        file.writerows(dataAll)
        f.close()
    again=input("假如要繼續請按y,不要繼續請按n: ")
    if again=='y':
        continue
    elif again=='n':
        break



然後打開execl,查詢到的門市都存在裡面了














留言

這個網誌中的熱門文章

(爬)微信公眾號上的圖片下載