Loading...

Python / / 2022. 5. 2. 12:50

파이썬 7강. 데이터 수집 - 크롤링

반응형

 

자바에서는 html을 다운받아 파싱 할 때 Jsoup를 썼는데,

파이썬에서는 beautifulSoup라는 html 파서를 사용한다.

 

https://pypi.org/project/beautifulsoup4/

 

beautifulsoup4

Screen-scraping library

pypi.org

 

$ python -m pip install beautifulsoup4

 

 

날씨 정보를 가져와보자.

from bs4 import BeautifulSoup

 

 

 

내가 필요한 데이터는 20도라는 숫자이다.

해당 숫자에 마우스 우클릭하여 검사해보니 blind라는 클래스로 감싸져 있다.

 

document.querySelector로 blind 돔을 찾아보면

blind 클래스로는 내가 원하는 데이터를 찾을 수 없다.

 

class는 디자인이기 때문에 다른곳에서 또 사용될 수 있기 때문이다.

 

좀 더 깊고 자세하게 찾아줘야한다.

document.querySelector(".weather_graphic .temperature_text strong");

 

똑같은 방법으로 beautifulsoup를 사용해 파싱 해보자.

# 크롤링
# python -m pip install beautifulsoup4

import requests
from bs4 import BeautifulSoup

html = requests.get(
    "https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=%EB%82%A0%EC%94%A8")

# json 데이터가 아닌 html 데이터이다!!
# print(html.text)

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

weather_el = soup.select_one(".weather_graphic .temperature_text strong")
print(weather_el)

 

html 태그까지 모두 추출되는 것을 볼 수 있다.

내부의 text만 추출하는 메서드가 있다.

print(weather_el.get_text())

 

 

 

[출처]

 

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com

메타 코딩 유튜브

https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형