• 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    미해결

연예뉴스크롤링의 CSS연산자 적용 및 no attribute 'text' 해결 방법

24.04.10 07:45 작성 24.04.10 07:47 수정 조회수 60

0

안녕하십니까, 강사님. 강의 잘 듣고 있습니다.

<연예뉴스크롤링>에서 뉴스 불러오기가 안돼 질문드립니다.

 이렇게 코드를 작성했습니다.

 

import requests

from bs4 import BeautifulSoup

import time

response = requests.get("https://entertain.naver.com/ranking/read?oid=076&aid=0004129264")

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")

else:

title = soup.select_one("#articleTitle")

content = soup.select_one("#newsct_article")

 

print(content.text)

 

이렇게 하면 이런 표시만 나옵니다.

C:\스타트코딩_크롤링>C:/Users/Sedaily/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/스타트코딩_크롤링/03_연예뉴스크롤링하기.py

 

그래서

else:

title = soup.select_one("#articleTitle") 의 CSS 연산자를 #news_tit로 바꿔서

 

else:

title = soup.select_one("#news_tit")

이렇게 하니 불러오기는 됩니다.

[1번 질문] 강의 마지막 부분에 ID 값이기 때문에 앞의 # 을 . 으로 변경하라고 알려주셨는데 그렇게 하면 안됩니다. html이 강의 당시와 변경돼 그런 건지, 이유가 궁금합니다.

 

[2번 질문] 마지막 부분의 print(content.text) 대신

링크, 제목, 본문 정리해서 가져오는 코드로 알려주신 이 코드를 밑에 붙이면

print("=======링크=======\n", url)

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

print("=======본문=======\n", content.text)

 

이렇게 표시가 됩니다. 해결 방법 알려주시면 감사하겠습니다.

 

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

https://n.news.naver.com/mnews/article/003/0012480442?sid=101

Traceback (most recent call last):

File "c:\스타트코딩_크롤링\03_연예뉴스크롤링하기.py", line 26, in <module>

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

^^^^^^^^^^

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

 

 

답변 1

답변을 작성해보세요.

0

코드가 들여쓰기 되어 있지 않아서 실행하기가 어렵네요 ㅜ

 

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

선택자가 올바르지 않아서 발생하는 오류입니다.

 

HTML 구조에 맞는 선택자만 똑바로 만들면 문제를 쉽게 해결할 수 있습니다.

 

이번에 새로 리뉴얼한 크롤링 기초 강의인데 한번 보시면

HTML 구조와 선택자를 만드는데 많은 도움이 되실 겁니다 🙂

https://youtu.be/Uf21RUo3KNc