티스토리 뷰

Data Science

파이썬을 이용한 동적 크롤링

호기심 많은 직장인 2022. 6. 2. 20:04

목차



    728x90

    오늘은 동적 크롤링에 대해서 작성해보겠습니다. 

     

    먼저 크롤링에 대해 얼마나 알고 계시나요?

    크롤링은 웹 페이지를 그대로 가져와서, 데이터를 그대로 추출해내는 행위

    .

    .

     

    보통 크롤링을 할 때는 BeautifulSoup 사용한다고 알고 계실겁니다.

    하지만 BeautifulSoup 라이브러리로는 동적 크롤링을 할 수 없습니다!

     

     

     

     

    "그렇다면 무슨 라이브러리를 사용해야 할까요?"

    .

    .

    .

     

    이번에 동적 데이터 크롤링을 위해 사용할 라이브러리는 바로 Selenium 입니다.

    Selenium은 원하는 웹 브라우저로 자유롭게 조작함으로서 자동화까지 가능하게 해주는 라이브러리입니다.

     

     

    지금부터 Selenium을 통해 태양 관측 사이트에서 태양 위치에 대한 데이터를 가져와보도록(크롤링) 하겠습니다.


    1. Selenium 라이브러리 불러오기

    from selenium import webdriver
    import datetime
    driver = webdriver.Chrome('C:/Users/ASUS/Downloads/chromedriver_win32/chromedriver')

    여기서 주의점은 크롬드라이버 이용 시 크롬버전과 크롬드라이버 버전이 같아야 실행이 가능하다는 점입니다!

     

     

     

    2. 크롤링 작동

    driver.implicitly_wait(1)
    for date in pd.date_range(start = "2019-01-01", end = '2019-01-01'):
        k = date.strftime("%Y-%m-%d")
        url = f"https://astro.kasi.re.kr/life/pageView/10?useElevation=1&lat=36.813805376962705&lng=127.05378294561001&elevation=-118.3559296513817&output_range=1&date={k}&hour=&minute=&second=&address=%EC%B6%A9%EC%B2%AD%EB%82%A8%EB%8F%84+%EC%95%84%EC%82%B0%EC%8B%9C+%ED%83%95%EC%A0%95%EB%A9%B4+%ED%83%95%EC%A0%95%EB%A1%9C+212"
        driver.get(url)
        driver.implicitly_wait(1)
    
        html = driver.page_source
        soup = BeautifulSoup(html, "html.parser")
    
        table=soup.find("table",{"class":"table tbl_cnt tbl_border tbl_center"})
        td = table.find_all("td")
        
    
        hour=[]
        one = []
        altitude=[]
        two = []
        three=[]
    
        for i in range(0,len(td)):
            if i%5==0:
                hour.append(td[i].text)
            elif i%5==1:
                one.append(td[i].text)
            elif i%5==2:
                altitude.append(td[i].text)
            elif i%5==3:
                two.append(td[i].text)
            elif i%5==4:
                three.append(td[i].text)
                
        df = pd.DataFrame(index=range(0,24), columns=theadList)
        df["시간(시)"] = hour
        df["방위각(도 분 초)"] = one
        df["고도(도 분 초)"] = altitude
        df["적경(시 분 초)"] = two
        df["적위(도 분 초)"] = three
        df["날짜"] = k

    driver.implicitly_wait() 는 간격을 넣는 함수입니다

    728x90
    반응형