파이썬 프로그램을 설치하지 않고 크롬 계열 브라우저에서 바로 파이썬을 실행할 수 있는 구글 코랩(Google Colab)을 이용해 실행할 예정입니다.

https://colab.research.google.com/ 

 

Google Colaboratory

 

colab.research.google.com

 

실행 화면입니다.

 

아래 코드를 실행하면 60개의 관련 뉴스를 링크와 함께 보여줍니다. (검색어 : 천문올림피아드)

import requests
from bs4 import BeautifulSoup

for i in range(1, 60, 10):

    url = "https://search.naver.com/search.naver?where=news&sm=tab_jum&query=천문올림피아드&start=" + str(i)

    response = requests.get(url)
    html = response.text

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

    for a_tag in soup.select('a.news_tit'):
        news_title = a_tag.text
        news_link = a_tag['href']
        print(news_title)
        print(news_link)
        print()

 


이제 코드를 해석해 보자. (검색어 : 천문올림피아드)

import requests                   # requests 라이브러리를 가져와.(웹페이지 내용을 가져오는 데 사용할거야)
from bs4 import BeautifulSoup     # bs4 모듈에서 BeautifulSoup 클래스를 가져와.(웹 페이지의 데이터를 추출하는 데 사용 할거야)

for i in range(1, 60, 10):        # 60개 뉴스를 불러들일거야.(페이지마다 10개 뉴스가 있으므로 start=1, 11, 21, 31, 41, 51을 불러들일거야)

    url = "https://search.naver.com/search.naver?where=news&sm=tab_jum&query=천문올림피아드&start=" + str(i)   # 검색어는 '천문올림피아드'로 해볼게.

    response = requests.get(url)     # requests 라이브러리를 사용하여 주어진 URL로 HTTP GET 요청을 보내서 웹 페이지 내용을 가져와. 
    html = response.text             # 웹 페이지의 내용을 가져와서 html 변수에 저장해.

    soup = BeautifulSoup(html, 'html.parser')     # BeautifulSoup을 사용하여 html의 HTML을 파싱해.

    for a_tag in soup.select('a.news_tit'):       # HTML의 <a>태그 중에서 클래스가 news_tit인 것을 선택해.(뉴스 제목을 포함하는 링크를 선택하는거야)
        news_title = a_tag.text                # 선택한 <a>태그의 텍스트 내용(뉴스 제목)을 news_title 변수에 저장해.
        news_link = a_tag['href']              # 선택한 <a>태그의 href 속성(뉴스 링크 URL)을 news_link 변수에 저장해.
        print(news_title)              # 뉴스 제목을 출력해.
        print(news_link)               # 뉴스 링크 URL을 출력해.
        print()                        # 각 뉴스 제목과 링크 사이에 빈 줄을 출력해.(가독성을 위한거야)

 

반응형

+ Recent posts