• 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    미해결

네이버 뉴스본문 가지고 오기도 되고 연예뉴스도 되는데 스포츠 뉴만 안되네요?

23.07.27 18:35 작성 조회수 362

0

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!
- 먼저 유사한 질문이 있었는지 검색해보세요.
- 서로 예의를 지키며 존중하는 문화를 만들어가요.
- 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.

AttributeError: 'NoneType' object has no attribute 'text'

이 오류가 계속 나오네요

연예뉴스 복사한후 바로 코드를 다시 썼는데도 안되네요 ㅠㅠ

import requests
from bs4 import BeautifulSoup
import time

response = requests.get("https://search.naver.com/search.naver?sm=tab_sug.top&where=news&query=%EC%86%90%ED%9D%A5%EB%AF%BC&oquery=%EB%B8%94%EB%9E%99%ED%95%91%ED%81%AC&tqi=iK4yElprvmZss69Ig8Nssssss1w-042517&acq=thsgmd&acr=1&qdt=0")
html = response.text
soup = BeautifulSoup(html,'html.parser')
articles = soup.select("div.info_group")
for article in articles:
    links = article.select("a.info")
    if len(links) >= 2:
        url = links[1].attrs["href"]

        response = requests.get(url,headers={'User-agent':'Mozila/5.0'})
        html = response.text
        soup = BeautifulSoup(html,'html.parser')

        # 만약 연예 뉴스라면
        if "entertain" in response.url:
            title = soup.select_one(".end_tit")
            content = soup.select_one ("#articeBody")
        elif "storts" in response.url:
            title = soup.select_one("h4.title")
            content = soup.select_one ("#newsEndContents")
            # 본문 내용안애 불필요한 div삭제
            divs = content.select("div")
            for div in divs:
                div.decompose()
            paragraphs = content.select("p")
            for p in paragraphs:
                p.decompose()
        else:
            title = soup.select_one("#artcleTitle")
            content = soup.select_one("#areicleBodyContents")
        print("============링크=========\n", url)
        print("============제목=========\n", title.text.strip())
        print("============본문=========\n", content.text.strip())
        
    time.sleep(0.3)

답변 2

·

답변을 작성해보세요.

0

yhahn02님의 프로필

yhahn02

2023.09.20

import requests
from bs4 import BeautifulSoup
import time
import pyautogui

keyword = pyautogui.prompt("검색어를 입력 하세요")
response = requests.get(f"https://search.naver.com/search.naver?sm=tab_sug.top&where=news&query={keyword}")
html = response.text
soup = BeautifulSoup(html,'html.parser')
articles = soup.select("div.info_group")
for article in articles:
    links = article.select("a.info")
    if len(links) >= 2:
        url = links[1].attrs["href"]

        response = requests.get(url,headers={'User-agent':'Mozila/5.0'})
        html = response.text
        soup = BeautifulSoup(html,'html.parser')

        # 만약 연예 뉴스라면
        if "entertain" in response.url:
            title = soup.select_one(".end_tit")
            content = soup.select_one ("#articeBody")
        elif "sports" in response.url:
            title = soup.select_one("h4.title")
            content = soup.select_one ("#newsEndContents")
            # 본문 내용안애 불필요한 div삭제
            divs = content.select("div")
            for div in divs:
                div.decompose()
            paragraphs = content.select("p")
            for p in paragraphs:
                p.decompose()
        else:
            title = soup.select_one("#artcleTitle")
            content = soup.select_one("#areicleBodyContents")
        print("============링크=========\n", url)
        print("============제목=========\n", title.text.strip())
        print("============본문=========\n", content.text.strip())
        
    time.sleep(0.3)

 

AttributeError: 'NoneType' object has no attribute 'text'

(base) tonyahn@Tonyui-MacBookPro vscode % /Users/tonyahn/anaconda3/bin/python /Users/tonyahn/Desktop/my_tony/vscode/Capter04/05.검색어변경하기

2023-09-20 15:55:35.653 python[10820:73580] TSM AdjustCapsLockLEDForKeyTransitionHandling - _ISSetPhysicalKeyboardCapsLockLED Inhibit

============링크=========

https://n.news.naver.com/mnews/article/277/0005312599?sid=102

Traceback (most recent call last):

File "/Users/tonyahn/Desktop/my_tony/vscode/Capter04/05.검색어변경하기", line 38, in <module>

print("============제목=========\n", title.text.strip())

^^^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'text'

(base) tonyahn@Tonyui-MacBookPro vscode % /Users/tonyahn/anaconda3/bin/python /Users/tonyahn/Desktop/my_tony/vscode/Capter04/05.검색어변경하기

2023-09-20 15:57:04.370 python[10846:74715] TSM AdjustCapsLockLEDForKeyTransitionHandling - _ISSetPhysicalKeyboardCapsLockLED Inhibit

============링크=========

https://n.news.naver.com/mnews/article/008/0004940773?sid=101

Traceback (most recent call last):

File "/Users/tonyahn/Desktop/my_tony/vscode/Capter04/05.검색어변경하기", line 38, in <module>

print("============제목=========\n", title.text.strip())

^^^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'text'

(base) tonyahn@Tonyui-MacBookPro vscode %

 

질문 : 검색어변경하기 후 이런 현상이 발생 합니다.

 

 

 

ad님의 프로필

ad

2023.09.21

https://n.news.naver.com/mnews/article/277/0005312599?sid=102

링크를 보면 일반뉴스인것 같은데 여기서 제목의 경우 네이버 내 CSS선택자가 강의 내용이랑 달라서 오류나는 것 같아요.

개발자 도구로 해당 뉴스 제목 검색했을 때 #title_area > span 으로 변경되었습니다.

연예뉴스나 스포츠뉴스는 그대로인데 일반 뉴스가 변경되어서 적용이 안되서 text 못찾는다고 하는 것 같아요.

아마 검색어 변경하기 하셨을 때는 해당 오류가 발생하지 않다가(연예/스포츠 검색시) 검색어 변경하기 코드 작성 후 일반뉴스가 나오는 검색어를 입력하셔서 해당 오류가 발생할 수도 있습니다.

 

개발자도구 이미지 같이 첨부드릴게요!

 

20230921_142623.png

ad님 답변 감사합니다 :)

0

"storts" 오타가 있네요!