지도 페이지에서 다수의 특정 정보들을 수집하기 위해서는 실제 사용자가 수행하는 동작에 대해 자동화가 필요하다.(각 페이지를 이동하며 정보를 확인 하는 등)
다음의 예제는 스타벅스 지도 페이지에서 광주의 스타벅스 매장에 대한 주소를 가져오는 실습니다.
- 총 5개의 지역이 있으며, 이때 페이지에서의 back() - 뒷 페이지로 이동하는 함수 -는 사용이 불가하다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | from selenium import webdriver as wb from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup as bs import time import requests as req import pandas as pd #매장 찾기 화면 생성 url = 'https://www.starbucks.co.kr/store/store_map.do' driver = wb.Chrome() driver.get(url) time.sleep(3) name = [] at = [] index_list = [] index_num = 1 #'지역 검색'로 이동 begin1 = driver.find_element_by_css_selector('#container > div > form > fieldset > div > section > article.find_store_cont > article > header.loca_search > h3 > a') begin1.click() #'지역 검색-광주'로 이동 gwangju = driver.find_element_by_css_selector('#container > div > form > fieldset > div > section > article.find_store_cont > article > article:nth-child(4) > div.loca_step1 > div.loca_step1_cont > ul > li:nth-child(3) > a') gwangju.click() #해당 페이지에서 각 지역에 대한 모든 지역 이동 링크 수집 time.sleep(1) gu = driver.find_elements_by_css_selector('.gugun_arae_box>li') #매장 찾기 for i in range(2,len(gu)+1) : #지역 검색 링크 reset = driver.find_element_by_css_selector('#container > div > form > fieldset > div > section > article.find_store_cont > article > header.loca_search > h3 > a') reset.click() time.sleep(1) #광주 이동 gwangju = driver.find_element_by_css_selector('#container > div > form > fieldset > div > section > article.find_store_cont > article > article:nth-child(4) > div.loca_step1 > div.loca_step1_cont > ul > li:nth-child(3) > a') gwangju.click() time.sleep(1) #광주의 각 지역 링크 이동 - '전체'제외 btn = driver.find_element_by_css_selector(f'#mCSB_2_container > ul > li:nth-child({i}) > a') btn.click() time.sleep(1) #각각의 지역에서 해당 지역의 매장의 정보를 수집 t = bs(driver.page_source,'lxml') name_t = t.select('#mCSB_3_container > ul > li > strong') at_t = t.select('#mCSB_3_container > ul > li > p') for j in range(len(name_t)) : name.append(name_t[j].text) at.append(at_t[j].text.replace(at_t[j].text[-9:],'')) index_list.append(index_num) index_num+=1 #데이터 프레임 출력 cafe_list = pd.DataFrame({'색인':index_list,'지점':name, '위치':at}) cafe_list.set_index('색인',inplace=True) display(cafe_list) | cs |

댓글
댓글 쓰기