import requests
from bs4 import BeautifulSoup
# code here
url = 'https://news.naver.com/breakingnews/section/101/258'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
financial = soup.find('div', {'class': 'section_latest'})
title = financial.find('ul', {'class': 'sa_list'}).find_all('a')
# for i in range(len(title)):
# print(title[i].get_text())
for element in title:
string = element.get_text()
print(string)
[단독] 최현만, 금융지주 ‘러브콜’ 고사 “사랑하는 미래에셋 창업멤버로 남겠다” [시그널]
새내기주 잔혹사 끊나… 쓰리빌리언 상장 첫날 15% 강세
카카오페이증권, 홍콩 기업과 AI 업무 자동화 협력
포인트엔지니어링, 3분기 흑자 전환 성공
어피니티, 원금 수준서 SSG 투자 ‘마침표’…이커머스 몸값 회복 ‘쉽지않네’ [투자360]
DI동일, 두번째 자사주 소각…보유분 65%
→ 문제점
① 첫 번째 Section에 있는 기사 6개 제목만 나옴
② 줄바꿈이 너무 많이 들어감: velog에서는 잘 안 보이는데 실제 실행 화면에서는 6줄씩 띄어져 있음…
import requests
from bs4 import BeautifulSoup
url = 'https://news.naver.com/breakingnews/section/101/258'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
financial = soup.find_all('strong', {'class': 'sa_text_strong'})
for element in financial:
title = element.get_text()
print(title, end='\n')
→ 생각했던 내용이 다 나왔음!
예제로 사용할 HTML 문서: 이상한 나라의 엘리스 이야기의 일부 "three sisters"
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
print(html_doc)
결과“three sisters” 문서를 뷰피플수프에 넣으면 BeautifulSoup 객체가 나오는데, 이 객체는 문서를 내포된 데이터 구조로 나타낸다:
.prettify()
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
print(soup.prettify())
soup.title
# <title>The Dormouse's story</title>
soup.title.name
# u'title'
soup.title.string
# u'The Dormouse's story'
soup.title.parent.name
# u'head'
soup.p
# <p class="title"><b>The Dormouse's story</b></p>
soup.p['class']
# u'title'
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
<a>
태그에 존재하는 모든 URL 추출for link in soup.find_all('a'):
print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie
print(soup.get_text())
# The Dormouse's story
#
# The Dormouse's story
#
# Once upon a time there were three little sisters; and their names were
# Elsie,
# Lacie and
# Tillie;
# and they lived at the bottom of a well.
#
# ...
soup.태그이름['class']
soup.find('태그이름')
또는 soup.select_one('태그이름')
soup.find_all('태그이름')
또는 soup.select('태그이름')
find_all
의 인수에는 리스트뿐만 아니라 문자열, 정규식도 들어갈 수 있음#1
fron bs4 import BeautifulSoup
bs = BeautifulSoup(html)
body_tag = bs.find('body')
list1 = body_tag.find_all(['p', 'img'])
for tag in list1:
print(tag)
: body 태그를 찾아서 body_tag에 넣어두고 find_all 함수에 리스트 형식으로 찾고 싶은 태그를 넣어줍니다. find_all 함수 실행 결과 p태그와 img태그를 모두 찾아서 리스트로 리턴합니다. 한 번에 여러 가지 태그를 조회하고 싶을 때는 위와 같은 방식으로 해주면 됩니다.
import re
tags = bs.find_all(re.compile("^p"))
find_all 함수에 전달할 수 안수는 태그이름, 속성, 문장, limit 등이 있음
속성 = "속성값"
의 형식bs.find_all(text=re.compile(" text +"))
bs.find_all('p', limit=2)
$ apt-get install python-lxml
$ easy_install lxml
$ pip install lxml
해석기 | 전형적 사용방법 | 장점 | 단점 |
---|---|---|---|
파이썬의 html.parser | BeautifulSoup(markup, "html.parser") | 각종 기능 완비, 적절한 속도, 관대함 (파이썬 2.7.3과 3.2에서.) | 별로 관대하지 않음 (파이썬 2.7.3이나 3.2.2 이전 버전에서) |
lxml의 HTML 해석기 | BeautifulSoup(markup, "lxml") | 아주 빠름, 관대함 | 외부 C 라이브러리 의존 |
lxml의 XML 해석기 | BeautifulSoup(markup, ["lxml", "xml"]) 또는 BeautifulSoup(markup, "xml") | 아주 빠름, 유일하게 XML 해석기 지원 | 외부 C 라이브러리 의존 |
html5lib | BeautifulSoup(markup, html5lib) | 아주 관대함, 웹 브라우저의 방식으로 페이지를 해석함, 유효한 HTML5를 생성함 | 아주 느림, 외부 파이썬 라이브러리 의존, 파이썬 2 전용 |
<div class=“my-class”></div>
를 보면 div 태그가 class 라는 값이 ‘my-class’인 attribute를 가지고 있음import requests
from bs4 import BeautifulSoup
url = "https://news.naver.com/breakingnews/section/101/258"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 요청이 제대로 들어갔는지 확인
response.status_code
[실행 결과]
200
titles = soup.find('strong', {'class':'sa_text_strong'})
titles
[실행 결과]
<strong class="sa_text_strong">[한경유레카 특징주] HMM, 3분기 호실적에 주가 상승세</strong>
# 모든 제목을 불러오고 싶을 때
titles = soup.find_all('a', {'class':'sa_text_title'})
for title in titles:
print(title.get_text())
titles = soup.findAll('a', {'class':'sa_text_title'})
라고 써도 됨
findAll
과 find_all
은 같은 기능을 하는 메서드임.get_text()
와 .text
의 차이
.text
는 property(get_text)
와 같음
객체.text
라고 쓰면 get_text
메서드 return값이 반환되는 것get_text와 text가 동일하긴 하지만 get_text()를 쓰게 되면 추가로 인자(Argument)를 매개변수(Parameter)에 넣을 수 있다는 장점이 있음
seperator=""
, strip=False
와 같이 파라미터가 기본으로 지정되어 있는데 호출 시 이를 활용해 seperator를 별도로 주어 연결시키거나 할 수 있는 것자세한 내용은 공식 문서 참고
titles = soup.find_all('strong', {'class':'sa_text_strong'})
for title in titles:
print(title.get_text)
for title in titles:
print(title.text)
sa_text_title._NLOG_IMPRESSION
# 꼭 제목의 제목의 HTML Tag를 가져올 필요는 없음
# 상위 Tag를 가져온 뒤 한 단계 더 깊게(한 번 더 find) 들어가도 됨!
titles = soup.find_all('a', {'class':'sa_text_title'})
for title in titles:
print(title.find('strong')
titles = soup.find_all('a', {'class':'sa_text_title'})
for title in titles:
print(title.find('strong').get_text())