python 내장 모듈 requests나 urllib을 이용해 HTML을 다운 받고, beautifulsoup으로 테이터를 추출한다.
웹 브라우저를 실제로 진행시키는 방법이기 때문에 속도도 많이 느리고, 메모리도 상대적으로 많이 차지한다.
서버에서 HTML을 다운 받기 때문에 javascipt 렌더링을 필요로 하는 사이트들은 크롤링하기 까다롭다.
Xpath란?
<!-- 우리가 찾아야할 것은 body라는 태그 하나로 끝나는 것이 아니다
각 태그에는 속성도 있고 속성값도 있고 태그의 내용물도 있다 -->
<html>
<body style="s2" class="top"> test </body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>2
</bookstore>
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
driver = webdriver.Chrome('../BI/driver/chromedriver.exe')
driver.get("https://www.opinet.co.kr/searRgSelect.do")
time.sleep(3)
# 가장싼주유소의 Xpath 경로
xpath="""//*[@id="quick_ul"]/li[2]/a/span"""
driver.find_element_by_xpath(xpath).click()
2. 주유소 가격 정보 저장
Xpath로 시군구 접근하기
from tqdm import notebook
# 시의 Xpath 경로
xpath="""//*[@id="SIDO_NM0"]/option[2]"""
driver.find_element_by_xpath(xpath).click()
for n in notebook.tqdm(range(1,27)):
# 구의 Xpath 경로
xpath='//*[@id="SIGUNGU_NM0"]/option'+'['+str(n)+']'
driver.find_element_by_xpath(xpath).click()
time.sleep(3)
#excel
xpath="""//*[@id="glopopd_excel"]/span"""
driver.find_element_by_xpath(xpath).click()
time.sleep(3)
새폴더를 만들어서 한곳에 넣기
엑셀 파일 확인
행을 기준으로 2번째까지는 필요없는 행이다.
엑셀파일 한번에 불러오기
from glob import glob
import pandas as pd
stations_files = glob("C:/Users/BI/Downloads/새 폴더/*.xls")
tmp = pd.read_excel(stations_files[0], header=2)
tmp.head(2)
불러온 데이터 합치기
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)
정보 확인
station_raw.info()
누락값이 없는걸 확인완료!!
필요 데이터만 추출
# 데이터 추출
stations = pd.DataFrame(
{
"상호" : station_raw.get("상호"),
"주소" : station_raw.get("주소"),
"가격" : station_raw.get("휘발유"),
"셀프" : station_raw.get("셀프여부"),
"상표" : station_raw.get("상표"),
}
)
# 구 정보 추가
stations["구"] = [eachAddress.split()[1] for eachAddress in stations.get("주소")]
# 가격 타입 변경
# 없는 값 제외
stations = stations[stations["가격"] != "-"]
# 타입 변경
stations["가격"] = stations["가격"].astype("float")
# 인덱스 번호 재설정
stations.reset_index(inplace=True)
# 이전의 index 컬럼 삭제
del stations['index']
stations.tail(2)