from class_time_line import TimeLine
from class_plan_date import PlanDate
from openpyxl.styles import Alignment, Font, Border, Side, PatternFill
from class_location import Location
import openpyxl
class ExcelConverter:
def __init__(self, timeline_obj: TimeLine = None):
self.time_line = timeline_obj
self.work_book = None
def make_workbook(self):
# 워크북 생성
wb = openpyxl.Workbook()
# 시트 활성화
ws = wb.worksheets[0] # wb.active 로 써도 됨
# 시트 이름바꾸기
ws.title = 'worksheet'
# 새로운 시트만들기
ws['B2'] = 'cell'
# 가운데 정렬
align_center = Alignment(horizontal='center', vertical='center')
# 글씨체 굵게
font_bold = Font(size=12, bold=True, color='000000') # 000000: black
# 셀 색깔 채우기
fill_blue = PatternFill('solid', fgColor='819FF7')
# 테두리 선넣기
thin_border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
# 위의 4가지 B2 cell에 적용시키기 + 값 'cell'에서 'text'로 바꾸기
ws['B2'].alignment = align_center
ws['B2'].font = font_bold
ws['B2'].fill = fill_blue
ws['B2'].border = thin_border
ws['B2'].value = 'text'
# 워크북 filename 으로 저장(없으면 새로생성)
filename = "../csv_data/test.xlsx"
wb.save(filename)
if __name__ == '__main__':
plan_date = PlanDate(1, '2023-04-05', '2023-04-08')
location = Location(7, '망상해수욕장', '1', '1.11111', '2.22222', '강원도어쩌구', '망상하는해수욕장')
location2 = Location(3, '해수욕장', '1', '1.41111', '2.62222', '강원도저쩌구', '그냥해수욕장')
location3 = Location(85, '오죽헌', '1', '1.41111', '2.62222', '강원도머시기', '오죽헌이올시다')
# conn.insert_plan_date(plan_date)
# conn.insert_location(location)
# print(a)
timeline = TimeLine(1, plan_date, [[location], [location2, location3], []], '사용자', '사용자여행')
ec = ExcelConverter(timeline)
ec.make_workbook()
크롤링 로직 구현

검색칸에 검색함 -> 해당 칸에 강원도 시·도·군 명이 들어가면 클릭을함
해당 클릭시 변경되는 URL

중에서 파싱하여 위도와 경도를 dictionary로 저장하여
엑셀파일로 저장하게함
정확도가 떨어지는 오류가 있으나 추후 디버깅 예정
def find_next_mark(current_index, url_str):
result = 0
for offset, c in enumerate(url_str[current_index + 3:]):
if c == "!":
result = offset
break
return result + 3
def parsing_gps_from_url(url_str: str):
w_do_idx = url_str.index('!3d')
w_do = url_str[w_do_idx + 3:w_do_idx + find_next_mark(w_do_idx, url_str)]
g_do_idx = url_str.index('!4d')
g_do = url_str[g_do_idx + 3:g_do_idx + find_next_mark(g_do_idx, url_str)]
return w_do, g_do
def find_gps_from_name_list(name_list: list[str]):
result_dict = dict()
gwd_domain_list = [
"춘천",
"원주",
"강릉",
"동해",
"태백",
"속초",
"삼척",
"홍천",
"횡성",
"영월",
"평창",
"정선",
"철원",
"화천",
"양구",
"인제",
"고성",
"양양",
]
driver = webdriver.Chrome()
driver.get(
"https://www.google.com/maps/place/%ED%9D%A5%EB%B3%B5%EC%97%AC%EC%9D%B8%EC%88%99/data=!3m1!4b1!4m6!3m5!1s0x3561c7aae80c7835:0x9e48007a6cb17619!8m2!3d37.5527958!4d129.1146664!16s%2Fg%2F11gh_swb34?entry=ttu")
driver.implicitly_wait(10)
text_area = driver.find_element(by=By.ID, value="searchboxinput")
for idx, name in enumerate(name_list):
print(idx, name)
text_area.clear()
text_area.send_keys(name)
time.sleep(5)
search_result_list = driver.find_elements(by=By.CLASS_NAME, value="fontBodyMedium")
search_relation_element = None
for div in search_result_list:
unique_name = div.text
is_has_relation = False
for li in gwd_domain_list:
if li in unique_name:
is_has_relation = True
search_relation_element = div
break
if is_has_relation is False:
result_dict.update({name: ("null", "null")})
else:
break
if search_relation_element is not None:
try:
search_relation_element.click()
time.sleep(5)
except Exception:
continue
url = driver.current_url
try:
w_do, g_do = parsing_gps_from_url(url)
result_dict.update({name: (w_do, g_do)})
except Exception:
w_do = "null"
g_do = "null"
finally:
result_dict.update({name: (w_do, g_do)})
else:
result_dict.update({name: ("null", "null")})
return result_dict
if __name__ == '__main__':
sample_list = """플라워펜션
플록스펜션
피그멜리온 이펙트"""
sample_list = sample_str.split('\n')
result_dict = find_gps_from_name_list(sample_list)
df = pd.DataFrame(result_dict, index=["위도", "경도"]).transpose()
print(df)
df.to_excel('saved_file.xlsx', engine="openpyxl")
그렇게 크롤링된 데이터들은
from class_time_line import TimeLine
from class_plan_date import PlanDate
from openpyxl.styles import Alignment, Font, Border, Side, PatternFill
from class_location import Location
import openpyxl
class ExcelConverter:
def __init__(self, timeline_obj: TimeLine = None):
self.time_line = timeline_obj
self.work_book = None
def make_workbook(self):
# 워크북 생성
wb = openpyxl.Workbook()
# 시트 활성화
ws = wb.worksheets[0] # wb.active 로 써도 됨
# 시트 이름바꾸기
ws.title = 'worksheet'
# 새로운 시트만들기
ws['B2'] = 'cell'
# 가운데 정렬
align_center = Alignment(horizontal='center', vertical='center')
# 글씨체 굵게
font_bold = Font(size=12, bold=True, color='000000') # 000000: black
# 셀 색깔 채우기
fill_blue = PatternFill('solid', fgColor='819FF7')
# 테두리 선넣기
thin_border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
# 위의 4가지 B2 cell에 적용시키기 + 값 'cell'에서 'text'로 바꾸기
ws['B2'].alignment = align_center
ws['B2'].font = font_bold
ws['B2'].fill = fill_blue
ws['B2'].border = thin_border
ws['B2'].value = 'text'
# 워크북 filename 으로 저장(없으면 새로생성)
filename = "../csv_data/test.xlsx"
wb.save(filename)
if __name__ == '__main__':
plan_date = PlanDate(1, '2023-04-05', '2023-04-08')
location = Location(7, '망상해수욕장', '1', '1.11111', '2.22222', '강원도어쩌구', '망상하는해수욕장')
location2 = Location(3, '해수욕장', '1', '1.41111', '2.62222', '강원도저쩌구', '그냥해수욕장')
location3 = Location(85, '오죽헌', '1', '1.41111', '2.62222', '강원도머시기', '오죽헌이올시다')
# conn.insert_plan_date(plan_date)
# conn.insert_location(location)
# print(a)
timeline = TimeLine(1, plan_date, [[location], [location2, location3], []], '사용자', '사용자여행')
ec = ExcelConverter(timeline)
ec.make_workbook()
엑셀파일로 저장하는 로직 구현 예정
금일은 곁가지로 필요한 로직을 이것저것 구현하면서 전체 일정을 확인하고, 프로젝트가 돌아가게끔 하다보니
1시간 일찍 퇴근하여 조금 쉬었습니다
다른 팀보다 진행도는 조금 느릴 수 있지만, 각 팀원이 모두 한계돌파하는 느낌으로 기술 스택을 늘리면서 trial 중입니다.
쉽지는 않지만 끝까지 계속 가보도록 하겠습니다.
감사합니다.
'광주인력개발원' 카테고리의 다른 글
[개발완료보고서] 5일차 | "봄 감자가 맛있단다" | 1조_무상광자 팀 | 강원도 여행 계획 프로그램 | (0) | 2023.07.09 |
---|---|
[개발일지] 4일차 | "봄 감자가 맛있단다" | 1조_무상광자 팀 | 강원도 여행 계획 프로그램 | (0) | 2023.07.09 |
[개발일지] 3일차 | "봄 감자가 맛있단다" | 1조_무상광자 팀 | 강원도 여행 계획 프로그램 | (0) | 2023.07.09 |
Applying Thread and Process on Python [2023-07-05 학습일지] (0) | 2023.07.09 |
[개발일지] 2일차 | "봄 감자가 맛있단다" | 1조_무상광자 팀 | 강원도 여행 계획 프로그램 | (0) | 2023.07.09 |