파이썬 다음 뉴스 스크래핑

1 개요[ | ]

파이썬 다음 뉴스 스크래핑

2 예시: 부제 없음[ | ]

import requests
from bs4 import BeautifulSoup, Comment

url = 'https://news.v.daum.net/v/20210612201912064'
r = requests.get(url, headers={'User-Agent':'Mozilla/5.0'})
soup = BeautifulSoup(r.text, 'html.parser')

# 제목 추출
title = soup.find("meta", property="og:title")
title = title["content"] if title else None

# 부제 추출
subtitle = soup.select_one('#mArticle .news_view strong.summary_view')
subtitle = subtitle.extract().text.strip() if subtitle else None

# 본문 추출
content = soup.select_one('#harmonyContainer section')
content = "".join([str(x) for x in content.contents])                      # 최상위 태그 제거(=innerHtml 추출)
content = content.strip()                                                  # 앞뒤 공백 제거

print('title=', title)       # 제목
print('subtitle=', subtitle) # 부제
print('content=', content)   # 본문

3 예시: 부제 있음[ | ]

import requests
from bs4 import BeautifulSoup, Comment

url = 'https://news.v.daum.net/v/20210612203811365'
r = requests.get(url, headers={'User-Agent':'Mozilla/5.0'})
soup = BeautifulSoup(r.text, 'html.parser')

# 제목 추출
title = soup.find("meta", property="og:title")
title = title["content"] if title else None

# 부제 추출
subtitle = soup.select_one('#mArticle .news_view strong.summary_view')
subtitle = subtitle.extract().text.strip() if subtitle else None

# 본문 추출
content = soup.select_one('#harmonyContainer section')
content = "".join([str(x) for x in content.contents])                      # 최상위 태그 제거(=innerHtml 추출)
content = content.strip()                                                  # 앞뒤 공백 제거

print('title=', title)       # 제목
print('subtitle=', subtitle) # 부제
print('content=', content)   # 본문

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}