conda install -c anaconda beautifulsoup4
pip install beautifulsoup4
data
- 3. test_first.html




from urllib.request import urlopen
url = "https://finance.naver.com/marketindex/"
page = urlopen(url)
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify( ))
# 방법 1
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://finance.naver.com/"
reponse = urlopen(url)
reponse.status
# 200 이라는 숫자가 정상적으로 요청을 했고, 정상적으로 받았다는 뜻
# http 상태코드라고 한다
# 번호에 따라서 웹페이지의 상태를 나타낸다
# 그 번호에 따라서 나의 잘못인지, 서버오류인지 등을 알 수 있다.
>>
200
# 방법 2
import requests
# from urllib.request.Request
# 위 requests 와 기능은 똑같다고는 하는데,
# from urllib.request.Request 는 실행하면 에러남
from bs4 import BeautifulSoup
url = "https://finance.naver.com/marketindex/"
reponse = requests.get(url)
# requests.get()
# requests.post()
# 두가지 방식이 있지만 설명은 안해줌
reponse
>> <Response [200]>
------------------------------------------------------
reponse.text
>> '\n<script language=javascript src="/template/....
------------------------------------------------------

# import
from bs4 import BeautifulSoup
import pandas as pd
page = open("../data/03. test_first.html", "r").read()
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify( ))

# Head 태그 확인
soup.head

# body 태그 확인
soup.body
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://finance.naver.com/"
reponse = urlopen(url)
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify())
soup.head # head tag 확인
soup.body # body tag 확인
soup.title # title tag 확인
soup.div # div tag 확인
soup.p # p tag 확인 (상단 하나만 나타남)

soup.find("p")
# 출력결과
<p class="inner-text first-item" id="first">
Happy PinkWink.
<a href="http://www.pinkwink.kr" id="pw-link">PinkWink</a>
</p>
# 조건을 좁혀주기
soup.find("p", class_="inner-text first-item")
# 출력결과
<p class="inner-text first-item" id="first">
Happy PinkWink.
<a href="http://www.pinkwink.kr" id="pw-link">PinkWink</a>
</p>

또는

soup.find_all(id = "pw-link")[PinkWink]
soup.find_all(id="pw-link")[0].text
'PinkWink'
soup.findall("p", class="inner-text second-item")
[
Happy Data Science.
Python
print(soup.find_all("p")[0].text)
print(soup.find_all("p")[1].string)
print(soup.find_all("p")[1].get_text())
Happy PinkWink.
PinkWink
None
Happy Data Science.
Python
soup.find("p",{"class":"outer-text first-item"}).text.strip()
### 실행결과

for each_tag in soup.find_all("p"):
print("=" * 50)
print(each_tag.text)

soup.find_all("li","on")(# li 태그의 on 클래스) 와 같은 방법
soup.find_all("p")
soup.find_all("p", class_="inner-text second-item")
soup.find_all(class_="outer-text")
soup.find_all(id="first")
soup.find_all(id="pw-link")[0].text
soup.find_all(id="pw-link")[0].string
soup.find_all(id="pw-link")[0].get_text()
soup.find_all(class_="outer-text")[0].text
soup.find(class_="outer-text").string
soup.find(class_="outer-text").get_text()

### strip - 공백지우기
soup.find("p", {"class": "outer-text first-item"}).text.strip()
실행결과
>> 'Data Science is Funny.'
soup.find("p", {"class":"inner-text first-item", "id":"first"}).text.strip()
### 실행결과
>> 'Happy PinkWink.'
- a 태그에서 href 속성값에 있는 값 추출
links = soup.find_all("a")
links[0].get("href"), links[1]["href"]
### 실행결과
('http://www.pinkwink.kr', 'https://www.python.org')
### 실행결과
PinkWink=>http://www.pinkwink.kr
Python=>https://www.python.org
tag_name : 태그 선택
.class : 클래스 선택
#id : 아이디 선택
> : 특정 요소의 자식 요소 선택
(space) : 특정 요소의 모든 하위 요소를 선택
[attribute] : attribute 속성을 가진 요소 선택
[attribute=value] : attribute 속성 값이 특정 값인 요소 선택
selector1, selector2 : selector1 또는 selector2 요소 선택
selector1 selector2 : selector1 내부의 모든 selector2요소 선택
title = exchangeList[0].select_one(".h_lst").text # '미국 USD'
exchange = exchangeList[0].select_one(".value").text # '1,319.00'
change = exchangeList[0].select_one(".change").text
updown = exchangeList[0].select_one("div.head_info.point_dn > .blind").text
exchangeList[0].select_one("a").get("href")

soup.find("p", class_="--")
soup.find("p", {"class":"--"})
위 2가지 모두 가능 (동일 반환값)
또는
soup.find("p", {"class":"--", "id":"--"})
soup.find("p", {"class": "outer-text first-item"}).text
soup.find("p", {"class": "outer-text first-item"}).get_text()
soup.find_all("a")[0].get("href")

links = soup.find_all("a")
# print(links)
### 실행결과
[<a href="http://www.pinkwink.kr" id="pw-link">PinkWink</a>,<a href="https://www.python.org" id="py-link">Python</a>]
'''
# print(links[0].get("href"), links[1]["href"])
for each in links:
href = each.get("href") # each["href"]
text = each.get_text()
print(text + " => " + href)