inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)

1단계 - class 선택자 고급 테크닉, 특수문자 처리 방법

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

577

남경민

작성한 질문수 1

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)

python 웹-크롤링

답변 2

0

yhahn02

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 %

 

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

 

 

 

0

ad

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

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

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

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

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

 

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

 

20230921_142623.png

0

스타트코딩

ad님 답변 감사합니다 :)

0

스타트코딩

"storts" 오타가 있네요!

셀레니움 환경설정 오류

0

45

2

네이버 로그인 관련

0

252

2

안녕하세요 셀레니움에 대해서 질문

0

84

1

크롤링 연습사이트 문의

0

95

2

선택자 질문

0

71

2

'특정 요소가 나타날 때까지 스크롤' 부분 에러

0

76

2

자동 로그인 질문

0

86

2

44강 제목, 링크

0

105

1

원하는 값이 없을 때

0

89

2

크롤링한 링크가 엑셀로 들어가면 작동이 안되요

0

227

2

셀레니움 PDF자료는 받을 수 있나요

0

100

2

글목록 추출하기

0

97

2

메일 자동화 로그인 중복방지문자해결 오류 및 명시적 대기 질문

0

88

2

강의 노트가 어디에 있는건가요?

0

80

2

강의 커리큘럼 질문

0

97

1

조건문 else 사용하지 않는 이유

0

75

2

셀레니움으로 접근할 수 없는 경우

0

95

2

웹페이지 변경

0

70

2

자바스크립트로 태그 선택 시 질문입니다.

1

64

2

수료증은 어떻게 받나요?

0

117

2

class명을 활용하여 선택자를 만들지 않는 경우..?

0

60

2

드라이버가 안 열려요

0

79

2

이거 해결방법 아시는 분?

0

121

2

네이버 지식인 크롤링..

0

201

2