카테고리 없음

웹에 있는 데이터를 구조화 실습.

jimmmy_jin 2025. 3. 9. 21:47

웹에 있는 세계 국가 데이터 가져와서 사용하기.

 

1. 페이지의 국가별 정보 확인(name, capital, popuilation, area)

2. 위 정보에 맞춰 class 만들기

class 에 들어와야할 데이터 타입 맞추고, area의 경우 승수 표시가 있어서

해당 부분 따로 계산 필요. (1.4e7 = 1.4 * 10^7 = 14,000,000)

 

from selenium import webdriver


class Country:
    # 지시사항 1번을 작성하세요.
    def __init__(self, name, capital, population, area):
        self.name = name
        self.capital = capital
        self.population = int(population)

        if 'E' in area:
            a,b = area.split('E')
            print(a,b)
            self.area = float(a) * (10 ** int(b))
        else:
            self.area = float(area)
    


with webdriver.Firefox() as driver:
    driver.get("https://www.scrapethissite.com/pages/simple/")

    # 지시사항 2번을 작성하세요.
    country_list = []
    div_list = driver.find_elements_by_class_name("country")

    for div in div_list:
        name = div.find_element_by_tag_name("h3").text
        capital = div.find_element_by_class_name("country-capital").text
        population = div.find_element_by_class_name("country-population").text
        area =  div.find_element_by_class_name("country-area").text

        country = Country(name, capital, population, area)
        country_list.append(country)

    # 지시사항 3번을 작성하세요.
    capital_list = []

    for country in country_list:
        capital_list.append(country.capital)
    
    capital_list.sort()
    print(capital_list[29])
    # 지시사항 4번을 작성하세요.

    pop_list = []
    for country in country_list:
        pop_list.append(country.population)

    print(sum(pop_list))

 

 

list로 가져올 경우 find_element / s 에서 오탈자 에러 주의

 

 

지시사항

  1. 웹에 있는 데이터를 구조화된 데이터(Structured Data)로 만들기 위해 class 를 먼저 정의합니다. 멤버 변수로 들어가야할 것은 다음과 같습니다.
    • 국가명
    • 수도
    • 인구
    • 면적
  2. 국가별 정보가 담긴 요소를 모두 가져오고, 각 요소를 파이썬 class인 Country의 인스턴스로 만들어 country_list 에 추가합니다.
  3. 모든 국가의 수도만 따로 list 를 만듭니다. 이 수도 목록을 sort() 또는 sorted() 를 이용하여 사전 순으로 정렬하고, 목록의 30번째 원소를 찾아 출력합니다.
  4. 흔히들 60억 지구촌이라는데, 이 데이터에선 과연 어떨까요? 모든 국가의 인구를 sum() 을 이용하여 더해서 출력합니다.