네이버 기사 크롤링 검색어 복수 입력

조회수 1376회

속보로 검색한 뉴스 검색 결과와 1보로 검색한 뉴스 검색 결과를 모두 출력하도록 하고 싶은데 어떻게 수정해야 하나요??

아래의 방법으로 사용하고있는데 지저분해 보여서요..

빠르고 친절한 답변을 주신 이루노님께 감사하지만 가능하면 큰 틀의 수정 없이 search_word 부분만 수정해서 사용하는 방법이 궁금합니다!!

import requests
from bs4 import BeautifulSoup

search_word = '속보'
url = f'https://search.naver.com/search.naver?where=news&query= 
{search_word}&sm=tab_srt&sort=1'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
news_titles = soup.select('.news .type01 li dt a[title]')

print()
for title in news_titles:
    print(title['title'])


search_word = '1보'
url = f'https://search.naver.com/search.naver?where=news&query= 
{search_word}&sm=tab_srt&sort=1'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
news_titles = soup.select('.news .type01 li dt a[title]')

print()
for title in news_titles:
    print(title['title'])

1 답변

  • 좋아요

    1

    싫어요
    채택 취소하기

    뉴스 결과를 검색하고 출력하는 과정을 함수로 표현하여 간략화했습니다.

    import requests
    from bs4 import BeautifulSoup
    
    def articles(search_word):
        # 뉴스 검색 및 출력하는 함수
        url = 'https://search.naver.com/search.naver?where=news&query=%s&sm=tab_srt&sort=1' % search_word
        r = requests.get(url)
        soup = BeautifulSoup(r.text, 'html.parser')
        news_titles = soup.select('.news .type01 li dt a[title]')
    
        print()
        for title in news_titles:
            print(title['title'])
    
    articles('속보')  # 속보 출력
    articles('1보')  # 1보 출력
    
    • (•́ ✖ •̀)
      알 수 없는 사용자
    • 친절한 답변 감사합니다. 죄송하지만 search_word 부분만 수정해서 사용할 수는 없을까요??? 초보자 2020.2.17 12:18
    • 제 수준에선 함수로 표현하는 코드가 한계인 것 같네요 ㅠㅠ 죄송합니다 알 수 없는 사용자 2020.2.18 12:37

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)