[BeautifulSoup] 다음 뉴스, 네이버 뉴스 기사 제목 크롤링 코드

리냥·2023년 7월 23일
0

안녕하세요!

오늘은 다음 뉴스기사와 네이버뉴스 기사 크롤링 코드를 배포합니다.

1. 다음 뉴스 제목 크롤링

# 패턴1. 라이브러리 로드

import requests
from bs4 import BeautifulSoup
head = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'}
url = 'https://news.naver.com/main/read.nhn?mode=LSD&mid=shm&sid1=102&oid=025&aid=0003065817'
res = requests.get(url,headers = head)

# 패턴2. 크롤링하고 싶은 페이지 URL넣음


# 패턴3. 데이터 구조화

soup = BeautifulSoup(res.content,'html.parser')

# 패턴4. 크롤링하고 싶은 내용 HTML 태그 지정


print(soup.select_one('#mArticle > div.head_view > h3').text, soup.select_one('#mArticle > div.head_view > div.info_view > span:nth-child(2) > span').text)

2. 네이버 뉴스 제목 크롤링

# 패턴1. 라이브러리 로드

import requests
from bs4 import BeautifulSoup

# 패턴2. 크롤링하고 싶은 페이지 URL넣음
#다음은 괜찮지만 네이버는 header를 넣어줘야함
head = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'}
url = 'https://n.news.naver.com/article/449/0000253878?cds=news_media_pc&type=editn'
res = requests.get(url,headers = head)

# 패턴3. 데이터 구조화

soup = BeautifulSoup(res.content,'html.parser')

# 패턴4. 크롤링하고 싶은 내용 HTML 태그 지정


print(soup.select_one('#title_area > span').text)
profile
안녕하세요. 일로 인해 잠시 쉽니다 :)

0개의 댓글