selenium 기초: https://velog.io/@one_step/selenium-%EA%B8%B0%EC%B4%88
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
url ="https://www.opinet.co.kr/searRgSelect.do"
driver = webdriver.Chrome('../driver/chromedriver')
driver.get(url)
# 지역 시/도
sido_list_raw = driver.find_element(By.ID, 'SIDO_NM0')
sido_list = sido_list_raw.find_elements(By.TAG_NAME, 'option')
sido_names = [option.get_attribute('value') for option in sido_list]
sido_names = sido_names[1:]
#서울특별시로 옵션 지정 실행
sido_list_raw.send_keys(sido_names[0])
gu_list_raw = driver.find_element(By.ID, 'SIGUNGU_NM0')
gu_list = gu_list_raw.find_elements(By.TAG_NAME, 'option')
gu_names = [option.get_attribute('value') for option in gu_list]
gu_names = gu_names[1:]
# 엑셀 저장
# 접근 차단 방지 및 selenium 실행 시간을 위해 sleep
import time
from tqdm import tqdm_notebook
for gu in tqdm_notebook(gu_names):
element = driver.find_element(By.ID, 'SIGUNGU_NM0')
element.send_keys(gu)
time.sleep(3)
element_get_excel = driver.find_element(By.CSS_SELECTOR, '#glopopd_excel').click()
time.sleep(3)
driver.quit()
from selenium import webdriver
from selenium.webdriver.common.by import By
import time # selenium 접속되고 시간이 걸려서 sleep을 해야 error 나지 않는다
def main_get():
url ="https://www.opinet.co.kr/searRgSelect.do"
driver = webdriver.Chrome('../driver/chromedriver')
driver.get(url)
time.sleep(3)
# 팝업창으로 화면 전환 후 닫아주기
driver.switch_to_window(driver.window_handles[-1])
driver.close()
time.sleep(3)
#메인화면 창으로 전환
driver.switch_to_window(driver.window_handles[-1])
#접근 url 다시 요청
driver.get(url)
import pandas as pd
from glob import glob
# 파일 목록 한 번에 불러오기
glob('../data/지역_*.xls')
# 파일명 저장
stations_files = glob('../data/지역_*.xls')
# 엑셀에 첫 번째, 두 번째 컬럼에 값이 없다 -> header
tmp_raw = []
for file_name in stations_files:
tmp = pd.read_excel(file_name, header=2)
tmp_raw.append(tmp)
station_raw = pd.concat(tmp_raw)
stations = pd.DataFrame({
"상호":station_raw["상호"],
"주소":station_raw["주소"],
"가격":station_raw["휘발유"],
"셀프":station_raw["셀프여부"],
"상표":station_raw["상표"]
})
stations["구"] = [eachAddress.split()[1] for eachAddress in stations['주소']]
# 가격정보 있는 정보만 사용
stations = stations[stations['가격'] != '-']
# 데이터 체크
stations.info()
# 인덱스 재정렬
stations.reset_index(inplace=True)
del stations['index']
stations.tail()
import matplotlib.pyplot as plt
import seaborn as sns
import platform
from matplotlib import font_manager, rc
get_ipython().run_line_magic('matplotlib', 'inline')
path = 'C:/Windows/Fonts/malgun.ttf'
if platform.system() == 'Darwin':
rc('font', family='Arial Unicode MS')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname=path).get_name()
rc('font', family=font_name)
else:
print('Unkown system sorry')
#boxplot(feat. pandas)
stations.boxplot(column='가격', by='셀프', figsize=(12,8))
# boxploy (feat. seaborn)
plt.figure(figsize=(12,8))
sns.boxplot(x='셀프', y='가격', data=stations, palette='Set2')
plt.grid(True)
plt.show()
# boxplot (feat. seaborn)
plt.figure(figsize=(12,8))
sns.boxplot(x='상표', y='가격', hue='셀프', data=stations, palette='Set3')
plt.grid(True)
plt.show()
import pandas as pd
import json
import folium
import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
gu_data = pd.pivot_table(data=stations, index='구', values='가격', aggfunc=np.mean)
geo_path = '../data/02. skorea_municipalities_geo_simple.json'
geo_str = json.load(open(geo_path, encoding='utf-8'))
my_map = folium.Map(location=[37.5502, 126.982], zoom_start=10.5, tiles='Stamen Toner')
my_map.choropleth(
geo_data=geo_str,
data=gu_data,
columns=[gu_data.index, '가격'],
key_on='feature.id',
fill_color='PuRd'
)
my_map
Reference
1) 제로베이스 데이터스쿨 강의자료