파이썬 웹 크롤링이용 텔레그램 챗봇1

임재성·2024년 1월 4일
0
해당 내용은 인프런의 한승우님의 '파이썬으로 영화 예매 오픈 알리미 만들기'를 하면서 오류가 발생했거나 어려웠던 점을 내용으로 쓰고 있습니다.

해당 강의를 들은 이유

  • 단순히 웹 크롤링을 한번도 하지 않아 간단한 강의영상을 보면서 진행하려고 하였다.
    인프런의 “영화예매” 라는 주제로 1시간짜리 강의영상이 존재하여 수강하였음.

난관..

  • cgv 홈페이지의 iframe에 들어가있는 태그들을 파이썬의 requests 모듈을 사용하여 응답으로 받는 내용이었으나....
  • 단순히 bs4를 사용하여 iframe의 값들을 들여다보면 빈 내용밖에 나오지 않음.
  • 개발자모드를 사용하여 본 결과 페이지가 로드된 후 자바스크립트를 통해 iframe내 데이터가 채워지는 방식으로 되어있음.
  • 그래서 인터넷 검색 결과 selenium 모듈을 사용하여 자바스크립트의 동작까지 기다려야 한다는 말을 보고 아래와 같이 코드 작성.

url='http://www.cgv.co.kr/theaters/?areacode=01&theaterCode=0013&date=20240103'

fromseleniumimportwebdriver
fromselenium.webdriver.common.byimportBy
fromselenium.webdriver.support.uiimportWebDriverWait
fromselenium.webdriver.supportimportexpected_conditionsasEC

#Selenium WebDriver를 초기화합니다. (ChromeDriver 사용 예제)
driver=webdriver.Chrome()

#대상 웹 페이지로 이동합니다.
driver.get(url)

#iframe의 XPath를 찾아서 해당 iframe으로 전환합니다.
iframe_xpath='//iframe[@id="ifrm_movie_time_table"]'  # 실제 웹 페이지의 iframe ID에 맞게 수정
iframe=WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, iframe_xpath))
)
driver.switch_to.frame(iframe)
print(driver.page_source)

하지만 나오지 않았음..

그래서 페이지 로드후 iframe 데이터를 가져오려면 다시 기다려야 하는듯 하여, 다음과 같이 코드 작성

url='http://www.cgv.co.kr/theaters/?areacode=01&theaterCode=0013&date=20240103'

fromseleniumimportwebdriver
fromselenium.webdriver.common.byimportBy
fromselenium.webdriver.support.uiimportWebDriverWait
fromselenium.webdriver.supportimportexpected_conditionsasEC

#Selenium WebDriver를 초기화합니다. (ChromeDriver 사용 예제)
driver=webdriver.Chrome()

#대상 웹 페이지로 이동합니다.
driver.get(url)

#iframe의 XPath를 찾아서 해당 iframe으로 전환합니다.
iframe_xpath='//iframe[@id="ifrm_movie_time_table"]'  # 실제 웹 페이지의 iframe ID에 맞게 수정
iframe=WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, iframe_xpath))
)
driver.switch_to.frame(iframe)

#iframe 내용이 로드될 때까지 대기합니다.
iframe_content_xpath='//div[@class="showtimes-wrap"]'  # 실제 웹 페이지의 iframe 내용에 맞게 수정
iframe_content=WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, iframe_content_xpath))
).get_attribute("outerHTML")

#iframe에서 벗어나 원래의 상위 레벨로 돌아갑니다.
driver.switch_to.default_content()

#WebDriver를 종료합니다.
driver.quit()

이렇게 하면 iframe의 javascriprt된 후의 내용을 볼 수 있음.

그리고 강의에서는 bs4사용했으므로,

soup = BeautifulSoup(iframe_content, 'html.parser')

다음 코드를 추가하여 bs4 모듈로 강의를 진행하도록 하였음.

문제점

  • 해당 코드는 리눅스에서 실행시 X 서비스를 통해 실행해야만 실행가능..
  • 코드를 실행해보면 크롬창이 새로 뜬 후 자바스크립트가 로드되고, iframe의 내용을 볼 수 있기 때문이다.

이후 텔레그램 챗봇에 관련된 내용은 다음 글에서 작성..

profile
조금씩 앞으로

0개의 댓글