프로젝트3 : 웹데이터 분석 4일차(~18)

박영선·2023년 5월 14일
0

selenium으로 데이터 얻어오기

오피넷 이용
https://www.opinet.co.kr/user/main/mainView.do

싼 주유소 찾기 - 지역별 클릭

셀레니움으로 페이지 접근

from selenium import webdriver
url = "https://www.opinet.co.kr/user/main/mainView.do"
driver = webdriver.Chrome("../driver/chromedriver/chromedriver.exe")
driver.get(url)
  • 문제 발생 (해당 URL이 아닌 메인페이지로 연결, 팝업창이 뜸)
# 팝업창 발생 및 다른화면 연결 시 해결 법
# 팝업창으로 전환
import time

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)

지역: 시/도 가져오기

sido_list_raw = driver.find_element_by_id("SIDO_NM0")
sido_list_raw.text

len(sido_list_raw.find_elements_by_tag_name("option"))

sido_list[1].get_attribute("value")

  • sido_names=[] : 밸류값들로 리스트 만들기
  • sido_names= sido_names[1:] : 맨앞 공백 빼고 리스트 다시 만들기

입력하기

sido_list_raw.send_keys(sido_names[16])

제주로 입력되어 있음

지역: 구 가져오기

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:]
gu_names[:5],len(gu_names)

gu_list_raw.send_keys(gu_names[3])

엑셀 다운받기

driver.find_element_by_css_selector("#glopopd_excel").click()
# xpath로 해보기
driver.find_element_by_xpath('//*[@id="glopopd_excel"]').click()

구 별 엑셀 다운받기

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_xpath('//*[@id="glopopd_excel"]').click()
    #엑셀파일 다운
    time.sleep(3)

가격정보 정리하기

엑셀 한번에 가져오기

glob("../data/oil/지역_*.xls")

# 파일명 저장
stations_files = glob("../data/oil/지역_*.xls")
stations_files[:5]

하나만 읽어보기

tmp = pd.read_excel(stations_files[0],header=2)
tmp.tail(2)

합치기

tmp_raw = []

for file_name in stations_files:
    tmp = pd.read_excel(file_name, header=2)
    tmp_raw.append(tmp)
    
# 형식이 동일하고 연달아 붙일때는 concat 사용

stations_raw = pd.concat(tmp_raw)
stations_raw
stations = pd.DataFrame({
    "상호":stations_raw["상호"],
    "주소":stations_raw["주소"],
    "가격":stations_raw["휘발유"],
    "셀프":stations_raw["셀프여부"],
    "상표":stations_raw["상표"]
})
stations.tail()

주소 구분하기

for eachAddress in stations["주소"]:
    print(eachAddress.split())

unique로 제대로 됐는지 확인

가격정보 확인하기

# 가격 정보 없는 주유소
stations[stations["가격"]=="-"]

# 가격정보가 있는 주유소만 사용
stations = stations[stations["가격"]!="-"]
stations.tail()

#가격정보 실수로 바꾸기
stations["가격"] = stations["가격"].astype("float")

인덱스 재정렬
(현재 각 엑셀별로 인덱스가 메겨져서 강남 13번 이후 강서 1번부터 다시 시작하는 식임)

주유가격 시각화

박스플롯을 통한 셀프여부와 가격 표시

지도 시각화

구별 평균값

지도 표시

profile
데이터분석 공부 시작했습니다

0개의 댓글