크롤링 script.string 오류 해결 방법(AttributeError: 'NoneType' object has no attribute 'string')

hh_mon__a·2024년 6월 27일
0

python

목록 보기
3/3
post-thumbnail

오류 상황

  • 크롤링하면서 script를 json으로 변경하는 곳에서 아래와 같은 오류 발생함.
# 원래 코드
script_json = json.loads(script.string) 
- 에러 메세지
AttributeError: 'NoneType' object has no attribute 'string'
  • 그러나 script를 확인해보니 내용이 존재함.

해결방법

  • script에는 내용이 존재하니, 이거를 직접 string으로 변환해야 함.
if script is not None: # 스크립트에 내용이 있다면
	script_content = script.string # .string 변환
    if script_content is None: # 변환한 값이 존재하지 않다면
    	# contents로 string으로 변경함
        script_content = ''.join(script.contents) 
        
	try:
		script_json = json.loads(script_content.strip()) # json형식으로 변경
		print(script_json)
	except json.JSONDecodeError as e:
		print("JSON 디코딩 에러:", e)
  • 이렇게 변경하니 json으로 변환이 되었으며, 적재가 잘되는 것을 알 수 있음.
profile
데이터분석/데이터사이언스/코딩

0개의 댓글