ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 시카고 샌드위치 맛집 분석하기
    Python 2018. 2. 22. 10:26

    시카고 매거진 홈페이지에 접속해서 샌드위치 가게 정보를 수집해서 지도에 표현하기


    # 패키지 로딩하기

    from bs4 import BeautifulSoup
    from urllib.request import urlopen
    import re
    from urllib.parse import urljoin
    import pandas as pd
    from tqdm import tqdm_notebook
    import folium
    import pandas as pd
    import googlemaps
    import numpy as np



    # 웹크롤링할 사이트
    url_base = "http://www.chicagomag.com"
    url_sub = "/Chicago-Magazine/November-2012/Best-Sandwiches-Chicago/"
    url = url_base + url_sub
    html = urlopen(url)
    soup = BeautifulSoup(html)



    # 순위, 메뉴, 카페 이름, 카페 주소 수집하기
    rank = []
    main_menu = []
    cafe_name = []
    url_add = []

    list_soup = soup.find_all("div", "sammy")
    for item in list_soup:
        rank.append(item.find(class_ = "sammyRank").get_text())
        tmp_string = item.find(class_ = "sammyListing").get_text()
        main_menu.append(re.split(("\n|\r\n"), tmp_string)[0])
        cafe_name.append(re.split(("\n|\r\n"), tmp_string)[1])
        url_add.append(urljoin(url_base, item.find("a")["href"]))



    # 데이터프레임 만들기
    chicagomag = {"Rank":rank, "Menu":main_menu, "Cafe":cafe_name, "URL":url_add}
    chicagomagDF = pd.DataFrame(chicagomag, columns = ["Rank", "Cafe", "Menu", "URL"])


    # 가격과 주소 추출하기
    price = []
    address = []
    for n in tqdm_notebook(chicagomagDF.index):
        html = urlopen(chicagomagDF["URL"][n])
        soup_tmp = BeautifulSoup(html, "lxml")
        gettings = soup_tmp.find("p", "addy").get_text()
        price.append(gettings.split()[0][:-1])
        address.append(" ".join(gettings.split()[1:-2]))



    # 데이터프레임에 Price, Address 열을 추가하기
    chicagomagDF["Price"] = price
    chicagomagDF["Address"] = address
    chicagomagDF = chicagomagDF.loc[:, ["Rank", "Cafe", "Menu", "Price", "Address"]]
    chicagomagDF.set_index("Rank", inplace = True)


    # googlemap에서 받은 키(key) 값 세팅하기
    gmaps_key = "xxxx"
    gmaps = googlemaps.Client(key = gmaps_key)



    # 카페에 대한 위도, 경도 수집하기
    lat = []
    lng = []

    for n in tqdm_notebook(chicagomagDF.index):
        if chicagomagDF["Address"][n] != "Multiple":
             target_name = chicagomagDF["Address"][n] + ", " + "Cicago"
            gmaps_output = gmaps.geocode(target_name)
            location_output = gmaps_output[0].get("geometry")
            lat.append(location_output["location"]["lat"])
            lng.append(location_output["location"]["lng"])
        else:
            lat.append(np.nan)
            lng.append(np.nan)



    # 데이터프레임에 lat, lng 열 추가하기
    chicagomagDF["lat"] = lat
    chicagomagDF["lng"] = lng



    # 지도에 카페 위치 표시하기
    mapping = folium.Map(location = [chicagomagDF["lat"].mean(), chicagomagDF["lng"].mean()], zoom_start = 11)

    for n in chicagomagDF.index:
        if chicagomagDF["Address"][n] != "Multiple":
            folium.Marker(location = [chicagomagDF["lat"][n], chicagomagDF["lng"][n]], 
            popup = chicagomagDF["Cafe"][n]).add_to(mapping)
    mapping


    자동 대체 텍스트를 사용할 수 없습니다.


    [출처] 파이썬으로 데이터 주무르기, 민형기 지음, BJPUBLIC, p139~158


Designed by Tistory.