one step
[파이썬] 국가명, 수도, 면적, 인구 추출해서 정리하기 본문
반응형
첫 번째 프로젝트
첫 번째 프로젝트는 이 웹페이지에서 진행합니다.
해당 페이지에 있는 다량의 데이터를 추출하고, 이를 가공함으로써 지금껏 배운 Selenium 과 Python 을 복습해보겠습니다.
지시사항
1) 웹에 있는 데이터를 구조화된 데이터(Structured Data)로 만들기 위해 class 를 먼저 정의합니다.
멤버 변수로 들어가야할 것은 다음과 같습니다.
국가명
수도
인구
면적
2) 국가별 정보가 담긴 요소를 모두 가져오고, 각 요소를 파이썬 class인 Country의 인스턴스로 만들어 country_list 에 추가합니다.
3) 모든 국가의 수도만 따로 list 를 만듭니다. 이 수도 목록을 sort() 또는 sorted() 를 이용하여 사전 순으로 정렬하고, 목록의 30번째 원소를 찾아 출력합니다.
4) 흔히들 60억 지구촌이라는데, 이 데이터에선 과연 어떨까요?
모든 국가의 인구를 sum() 을 이용하여 더해서 출력합니다.
Tips!
1) 리스트에서 nnn 번째인 원소를 찾는 방법
index는 000 부터 시작하므로, nnn 번째 원소의 index는 n−1
2) 면적 데이터는 아래 예시처럼 숫자가 아닌 표현으로 있을 수 있기 때문에, 그런 경우엔 변환을 해줘야 합니다.
1.4e7 = 1.4 * 10^7 = 14,000,000
# 초기 코드
from selenium import webdriver
class Country:
# 지시사항 1번을 작성하세요.
with webdriver.Firefox() as driver:
driver.get("https://www.scrapethissite.com/pages/simple/")
# 지시사항 2번을 작성하세요.
country_list = []
# 지시사항 3번을 작성하세요.
capital_list = []
# 지시사항 4번을 작성하세요.
# 완성 코드
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')
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_class_name('country-name').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번을 작성하세요.
global_pop = 0
for country in country_list:
global_pop += country.population
print(global_pop)
반응형
'이것저것 코드 > 파이썬' 카테고리의 다른 글
[파이썬] 비동기 화면 크롤링하기 (wait 사용하기) (0) | 2022.09.16 |
---|---|
[파이썬] 페이지네이션 있는 페이지에서 값 추출 및 딕셔너리 만들기 (1) | 2022.09.16 |
[파이썬] Action chain 사용해서 ID/PW입력받고 로그인 버튼 누르고, 환영 메시지 출력하기 (0) | 2022.09.10 |
[파이썬] 클래스, 메서드. 서로 다른 메서드에서 초기값 호출하기 (코멘트 관리) (0) | 2022.09.08 |
[파이썬] 꺾은선 그래프 그리기 (토끼그림) (0) | 2022.09.08 |