<!DOCTYPE html>
<html>
<head>
<title>Very Simple HTML Code by SY</title>
</head>
<body>
<div>
<p clases = "inner-text first-item" id="first">
Happy Zerobase.
<a href="http://www.pinkwink.kr" id="pw-link">PinkWink</a>
</p>
<p class="inner-text second-item">
Happy Data Science.
<a href="https://www.python.org" target="_blink" id="py-link">Python</a>
</p>
</div>
<p class="outer-text first-item" id="second">
<b>Data Science is funny.</b>
</p>
<p class="outer-text">
<i>All I need is love.</i>
</p>
</body>
</html>

<head>: 상단 창바의 이름<body>: 실제 창 구성<a href="링크" id="id값">텍스트명</a>: 하이퍼링크 생성target="_blink": 클릭해서 창을 열 때 새로운 창으로 열림<b></b>: 볼드체<i></i>: 기울임체1) from bs4 import BeautifulSoup
2) html 오픈해서 BeaufitulSoup으로 읽기
page = open("../data/03. zerobase.html", "r").read()
soup = BeautifulSoup(page, "html.parser")
#page에 있는 내용을 BeautifulSoup으로 읽기
#Parser: https://www.crummy.com/software/BeautifulSoup/bs4/doc/ (어떤 엔진을 사용할지)
print(soup.prettify()) # html을 들여쓰기해서 좀 더 보기 편하게 만들기
1) 간단한 방법
2) soup.find()
soup.find("p")soup.find("p", class_="inner-text second-item")soup.find("p", {"class":"outer-text first-item"})soup.find("p", {"class":"outer-text first-item"}).text.strip() soup.find("p", {"class":"inner-text first-item", "id": "first"})3) soup.find_all()
soup.find_all("p"): 모든 p태그 반환 soup.find_all(class_="outer-text"): 해당하는 2개의 p태그 불러옴soup.find_all(id="pw-link")[0].text: 리스트이기 때문에 [0]와 같이 인덱스 지정 필요4) p태그 리스트에서 텍스트 속성만 출력하기
.text / .get_text()# print와 함께 사용하면 예쁘게 출력됨
print(soup.find_all("p")[1].text)
print(soup.find_all("p")[1].get_text())
print(soup.find_all("p")[1].string)
for each_tag in soup.find_all("p"):
print("="*50)
print(each_tag.text)
...
==================================================
Happy Zerobase.
PinkWink
==================================================
Happy Data Science.
Python
==================================================
Data Science is funny.
==================================================
All I need is love.
5) a 태그에서 href 속성값에 있는 링크 추출
soup.find_all("a")[0].get("href")soup.find_all("a")[0]["href"]links = soup.find_all("a")
links[0].get("href"), links[1]["href"]
...
('http://www.pinkwink.kr', 'https://www.python.org')
for each in links:
href = each.get("href") #혹은: each["href"]
text = each.get_text()
print(text+" -> "+href)
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://finance.naver.com/marketindex/"
response = urlopen(url)
soup = BeautifulSoup(response, "html.parser")
print(soup.prettify())
-response.status: URL 읽어주는 Request에 대한 HTTP 상태 코드
1) 터미널에서 requests 설치
pip install requests
pip list | grep requests: requests 설치되었는지, 버전과 함께 확인
2) VS Code에서 import
import requests # from urllib.request.Request 와 유사 => 편한 것 사용
from bs4 import BeautifulSoup
3) 페이지 url 불러오기
url = "https://finance.naver.com/marketindex/"
response = requests.get(url) #requests.post() 방식도 있음.
response.text / response.content: html 전체 출력response: request status 확인soup = BeautifulSoup(response.text, "html.parser")
print(soup.prettify())
exchangeList = soup.select("#exchangeList > li")
# 즉, exchangeList라는 id를 가진 태그 중에서 하위에 li 태그 불러오기
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
# class="head_info point_up"와 같이 띄어쓰기 있을 때는 class가 2개인 것으로 인식함 -> select에서 불러올 때는 사이에 '.'을 붙여줌
# '>'의 의미: 바로 하위에 있는 클래스의 값을 가져오는 것
baseUrl = "https://finance.naver.com"
link = baseUrl + exchangeList[0].select_one("a").get("href")
title, exchange, change, updown, link
...
('미국 USD', '1,377.00', '3.50', '상승', 'https://finance.naver.com/marketindex/exchangeDetail.naver?marketindexCd=FX_USDKRW')
from urllib.request import urlopen, Request
import urllib
html = "https://ko.wikipedia.org/wiki/{search_words}"
#https://ko.wikipedia.org/wiki/여명의_눈동자
req = Request(html.format(search_words=urllib.parse.quote("여명의_눈동자")))
#글자를 URL로 인코딩 -> 한글을 encoding/decoding해주는 사이트 사용하여 입력해도 됨.
response = urlopen(req)
soup = BeautifulSoup(response, "html.parser")
print(soup.prettify())
# 출력하려는 텍스트값이 몇번째 줄에 존재하는지 확인하는 용도 (ul이 너무 많음!)
n=0
for each in soup.find_all("ul"):
print("=>" + str(n) + "=========")
print(each.get_text())
n += 1
soup.find_all("ul")[35].text.strip().replace("\xa0", "").replace("\n","")
req = Request(url, headers={"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"})req = Request(url, headers={"User-Agent": "Chrome"})from fake_useragent import UserAgent
ua = UserAgent()
ua.ie #Fake인 User Agent를 랜덤하게 반환함.
req = Request(url, headers={"user-agent": ua.ie})
#Fake로 받아온 user-agent를 입력해도 됨.
from urllib.parse import urljoinurl_add.append(urljoin(url_base, item.select_one("a").get("href")))import re(참고)
df.to_excel("./03. naverfinance.xlsx", encoding="utf-8") 했을 때,to_excel() got an unexpected keyword argument 'encoding' 에러 발생