네이버 뉴스 크롤링하기

Amps93·2023년 2월 25일
0

beautifulsoup

목록 보기
2/2

2월25일 IT/과학 > IT일반 탭의 기사를 크롤링하려고 한다. 먼저 해당 페이지에 접속 후 url을 확인한다.

https://news.naver.com/main/list.naver?mode=LS2D&sid2=230&sid1=105&mid=shm&date=20230225&page=1

해당 url에 접속해 데이터를 읽어오려고 하면 아래와 같은 오류가 발생한다.

url = 'https://news.naver.com/main/list.naver?mode=LS2D&sid2=731&sid1=105&mid=shm&date=20230225&page=1'

html = requests.get(url, headers=header)
soup = BeautifulSoup(html.text, 'html.parser')
          
print(soup.title)

ConnectionError: ('Connection aborted.', ConnectionResetError(10054, '현재 연결은 원격 호스트에 의해 강제로 끊겼습니다', None, 10054, None))

소켓 연결 실패 시 발생하는 오류로 네이버에서 크롤링을 차단하기 위해 설정해 놓은 것이다. 헤더를 추가해 문제를 해결 할 수 있음.

url = 'https://news.naver.com/main/list.naver?mode=LS2D&sid2=731&sid1=105&mid=shm&date=20230225&page=1'
# header 추가
header = {"user-agent": "Mozilla/5.0"}

html = requests.get(url, headers=header)
soup = BeautifulSoup(html.text, 'html.parser')
          
print(soup.title)

# 결과
> <title>IT/과학 홈 : 네이버 뉴스	</title>

우선 2월25일 IT일반 모든 기사의 url을 가져온다. 크롬 개발자도구(F12)를 통해 기사 url이 들어있는 html태그를 확인한다.

#main_content > div.list_body.newsflash_body > ul.type06_headline > li:nth-child(1) > dl > dt:nth-child(2) > a

li:nth-child(숫자) 형식으로 숫자가 1씩 증가하는 형식으로 되어있다. 이를 토대로 링크를 불러온다.

link_li = []

for i in range(1,11):
    link_li.append(soup.select('#main_content > div.list_body.newsflash_body > ul.type06_headline > li:nth-of-type(' + str(i) + ') > dl > dt > a')[0].attrs['href'])
    
for i in range(1, 11):
    link_li.append(soup.select('#main_content > div.list_body.newsflash_body > ul.type06 > li:nth-of-type(' + str(i) + ') > dl > dt > a')[0].attrs['href'])

이제 link_li에 있는 링크에 하나씩 접속하며 title, description, date를 가져오는 코드를 작성한다.

title_lst = []
description_lst = []
date_lst = []

for link in link_li:
    header = {"user-agent": "Mozilla/5.0"}

    html = requests.get(link, headers=header)
    soup = BeautifulSoup(html.text, 'html.parser')
    

    title = soup.find('h2', {'id': 'title_area'})
    title_lst.append(title.text)


    description = soup.find('div', {'id': 'dic_area'})
    description = description.text
    description_lst.append(description)

    date = soup.find('span', {'class': 'media_end_head_info_datestamp_time _ARTICLE_DATE_TIME'})
    date = date['data-date-time']
    date_lst.append(date)
    
df = pd.DataFrame(zip(date_lst, title_lst, description_lst), columns=['date', 'title', 'description'])

전체 코드는 아래에서 확인 가능
https://github.com/amps93/naver_crawling

profile
머신러닝 개발자

0개의 댓글