- conda install -c anaconda beautifulsoup4
- pip install beautifulsoup4
!pip install requests
1)
from bs4 import BeautifulSoup
page = open("파일명", "r").read()
print(page)
2)
page = open("파일명", "r").read()
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify())
1)
soup.find("p")
2)
soup.find("p", class_="inner-text second-item")
3) dict
soup.find("p", {"class":"outer-text first-item"}).text.strip()
4) 다중 조건
soup.find("p", {"class" : "inner-text first-item", "id" : "first"})
1) 특정 태그 확인
soup.find_all(class_="outer-text")
2) 리스트 형태의 text 반환시 인덱스 설정
soup.find_all(id="pw-link")[0].text

환율 지표 확인하기
- 개발자 도구(f12)를 통해 html 데이터 확인하기
html 가져오기
+ import requests (from urllib.requests.Request)
- response = requests.get()
- requests.post()
원하는 데이터 추출하기
* 모두 같은 반환을 하는 코드 soup.find_all("span", "value") soup.find_all("span", class_="value") soup.find_all("span", {"class":"value"})text만 추출하기
* 모두 같은 반환을 하는 코드 soup.find_all("span", "value")[0].text, soup.find_all("span", {"class":"value"})[0].string, soup.find_all("span", {"class":"value"})[0].get_text()
추출한 데이터의 원하는 값 확인하기
- '>' : 해당 태그의 하위를 반환
exchangeList = soup.select("#exchangeList > li")
각 데이터의 해당하는 태그 반환하기
- head_info point_dn 띄어쓰기는 none 반환 : 띄어쓰기는 "." 으로 이어주기
baseUrl = "https://finance.naver.com"
baseUrl + exchangeList[0].select_one("a").get("href")
exchange_datas = []
baseUrl = "https://finance.naver.com"
for item in exchangeList:
data = {
"title": item.select_one(".h_lst").text,
"exchnage": item.select_one(".value").text,
"change": item.select_one(".change").text,
"updown": item.select_one(".head_info.point_dn > .blind").text,
"link": baseUrl + item.select_one("a").get("href")
}
exchange_datas.append(data)
df = pd.DataFrame(exchange_datas)
df.to_excel("./naverfinance.xlsx", encoding="utf-8")
import urllib
from urllib.request import urlopen, Request
html = "https://ko.wikipedia.org/wiki/{search_words}"
# 글자를 URL로 인코딩
req = Request(html.format(search_words=urllib.parse.quote("여명의_눈동자")))
response = urlopen(req)
soup = BeautifulSoup(response, "html.parser")
print(soup.prettify())
“이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.”