Zerobase DS School

[데이터 취업 스쿨 스터디 노트] BeautifulSoup / 크롤링 / 웹데이터 분석 1 - 2

Sehe_e 2024. 8. 5. 22:20

 


 

BeautifulSoup Basic

 

BeautifulSoup 설치

conda install -c anaconda beautifulsoup4

pip install beautifulsoup

 

BeautifulSoup import

from bs4 import BeautifulSoup

page = open('../data/03. zerobase.html', 'r').read()
soup = BeautifulSoup(page, 'html.parser')
# prettify() : 들여쓰기
print(soup.prettify())

 

html 태그 조회

# 제일 상단의 p 태그를 조회한다.
soup.p

 

단일 선택 : find, select_one

# class_, id_ 인자값을 통해 조회할 수 있다.
# class : . / id : #

# 1
soup.find('p', class_='innter-text second-item')

# 2
soup.find('p', 'innter-text second-item')

# 3
soup.select_one('p.innter-text.second-item')

 

검색 조건 다중 설정 가능

# 다중 조건. 조건을 여러 개 설정하여 조회할 수 있다.
soup.find('p', {'class':'inner-text first-item', 'id':'first'})

 

다중 선택 : find_all, select

# 인자로 넣은 태그를 전부 찾으며 리스트로 반환한다.
soup.find_all('p')

 

text 가져오기

# 특정 class나 id를 가진 태그를 조회할 수 있으며 특정 인덱스 값으로 내용을 가져올 수 있다.

# 1
print(soup.find_all(id='pw-link')[0].text)

# 2
print(soup.find_all(id='pw-link')[0].string)

# 3
print(soup.find_all(id='pw-link')[0].get_text())

 

하이퍼링크 가져오기

# a 태그에서 href 속성값에 있는 값 추출
links = soup.find_all('a')
print(links)

# 1
print(links[0].get('href'))
# 2
print(links[1]['href'])

 

 


 

BeautifulSoup 예제 1-1 네이버금융

 

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://finance.naver.com/marketindex/'
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
print(soup.prettify())

생략

 

span 태그의 class = value 찾기

# 1
soup.find_all('span', 'value')

# 2
soup.find_all('span', class_='value')

# 3
soup.find_all('span', {'class':'value'})

 

 


 

BeautifulSoup 예제 1-2 네이버금융

 

requests 설치

! pip install requests

 

import requests
from bs4 import BeautifulSoup

url = 'https://finance.naver.com/marketindex/'
response = requests.get(url)

# 상태 코드 확인
# print(response)    # 200

soup = BeautifulSoup(response.text, 'html.parser')
print(soup.prettify())

생략

 

select로 id = exchangeList 의 하위 li 태그 전부 가져오기

 > : 하위 태그

# soup.find_all('li', 'on')
exchangeList = soup.select('#exchangeList > li')
len(exchangeList), exchangeList

 

exchangeList에서 select_one으로 종목, 거래가, 변동폭, 변동추세를 가져오기

title = exchangeList[0].select_one('.h_lst').text
exchange = exchangeList[0].select_one('.value').text
change = exchangeList[0].select_one('.change').text
updown = exchangeList[0].select_one('div.head_info.point_up > .blind').text

title, exchange, change, updown



종목 상세페이지로 이동하는 하이퍼링크 가져오기. 상대주소로 되어있어 절대주소로 만들어준다.

baseUrl = 'https://finance.naver.com'
baseUrl + exchangeList[0].select_one('a').get('href')

 

데이터를 수집하여 DataFrame으로 만든 후 저장

# 4개 데이터 수집

import pandas as pd
exchange_datas = []
baseUrl = 'https://finance.naver.com'

for item in exchangeList:
    data = {
        'title' : item.select_one('.h_lst').text,
        'exchange': item.select_one('.value').text,
        'change': item.select_one('.change').text,
        'updown': exchangeList[0].select_one('div.head_info.point_up > .blind').text,
        'link': baseUrl + exchangeList[0].select_one('a').get('href')
    }
    exchange_datas.append(data)

df = pd.DataFrame(exchange_datas)
print(df)
df.to_excel('./naverfinance.xlsx')

 

 


 

BeautifulSoup 예제 2 위키백과 문서 정보 가져오기

 

드라마 '여명의 눈동자' 주연 정보 가져오기

 

from urllib.request import urlopen, Request
import urllib

# 웹사이트에서 decoding 실행
# html = 'https://ko.wikipedia.org/wiki/여명의_눈동자'

# 한글를 URL로 디코딩
html = 'https://ko.wikipedia.org/wiki/{search_words}'
req = Request(html.format(search_words=urllib.parse.quote('여명의_눈동자')))

response = urlopen(req)
soup = BeautifulSoup(response, 'html.parser')
print(soup.prettify())

생략

 

태그에 순서를 매겨 내가 필요한 정보 위치 파악하기

n = 0

for each in soup.find_all('ul'):
    print(' => '+ str(n) + ' ====================')
    print(each.get_text().split('\n'))
    n += 1

 

텍스트 위치 특정하여 출력

soup.find_all('ul')[35].text

 

텍스트 다듬어 정리하기

soup.find_all('ul')[35].text.replace('\xa0', '').replace('\n', '')

 

 


내일의 학습 목표

웹데이터분석 3 - 5