커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
bs4 .text() 질문 + 파이썬 try,except문
undefined주차
북마크
백*현
댓글
1
추천
0
조회수
10
조회수
10
답변 완료



import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient

client = MongoClient('mongodb+srv://test:sparta@cluster0.clu05af.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701', headers=headers)

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

musics = soup.select('tbody> .list')


for music in musics:
    if music is not None:

        try:
            temp_rank = music.select_one('td.number').text
            del_rank = music.select_one('td.number >span').text
            temp_title = music.select_one('td.info >a').text
            del_icon = music.select_one('.icon icon-19').text
            temp_musician = music.select_one('td.info >.artist.ellipsis').text

        except AttributeError : print(del_rank,del_icon)

        finally:
            rank = temp_rank.replace(del_rank,'').strip()
            title = temp_title.replace(del_icon,'').strip()
            musician = temp_musician.strip()

            print(rank,title,musician)

           # temp_type = {'rank': rank,
            #             'title': title,
             #            'musician': musician }

            #db.musiclist.insert_one(temp_type);


해당 부분에서 다음과 같은 에러가 떠서요


Traceback (most recent call last):

 File "C:/Users/dpfla/PycharmProjects/pythonProject1/homework.py", line 24, in <module>

  del_icon = music.select_one('icon icon-19').text

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


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

 File "C:/Users/dpfla/PycharmProjects/pythonProject1/homework.py", line 27, in <module>

  except AttributeError : print(del_rank,del_icon)

NameError: name 'del_icon' is not defined


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

 File "C:/Users/dpfla/PycharmProjects/pythonProject1/homework.py", line 33, in <module>

  title = temp_title.replace(del_icon,'').strip()

NameError: name 'del_icon' is not defined



우선 del_icon을 제외하면 해당 코드가 정상적으로 작동합니다.


Attribute Error는 icon 객체가 가져올 때 null 이라 text-attribute를 정의 할 수 없어서


except 구문에 Attribute error를 설정해 놨는데 왜 에러 창에 뜨는지 ..



Name Error가 뜨는거라면 del_icon을 정의한 부분에서 코드가 죽은 것 같은데..


try 구문에서 왜이러는지 잘 모르겠어요 ㅜㅜ.


덧붙여 bs 한글판 문서를 봐도. .text가 자손 및 후손의 innerhtml의 값을 모두 데려오더라구요

선택자의 text만 가져오게 하고 싶은데 해당 함수를 찾아봐도 보이지 않는 것 같은데..


혹시 해당 함수가 있다면 알려주시면 감사하겠습니다.








취소
 공유
취소
댓글 0
댓글 알림
나의얼굴