-
블로그 글 내용 저장 중 이모지 '\U0001f970' 에러 발생 (파이썬)코딩 연습/코딩배우기 2021. 12. 26. 20:42
블로그 글 내용을 파이썬으로 스크래핑(크롤링)하여 저장 중에 발생한 아래와 같은 에러 메시지( UnicodeEncodeError: 'cp949' codec can't encode character '\U0001f970' in position 1806: illegal multibyte sequence)를 조치하기 구글에서 찾아봤다.
이모지(emoji)로 인한 유니코드 인코딩 에러
블로그 글 내용을 저장하기 위해 아래와 같이 코딩했으나... 에러 메시지가 나왔다.
with open(keyword + '/' + '블로그 본문 내용들.txt', 'a') as f: f.write(body_contents)
\U0001f970 - 이모지( emoji) 에러 메시지 중 '\U0001f970'를 찾아보니 이모지(emoji) 웃는 얼굴이라고 나왔다.
Unicode Character 'SMILING FACE WITH SMILING EYES AND THREE HEARTS' (U+1F970)
이모지를 없애는 코드도 있었다.
import re def remove_emoji(string): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r'', string)
import re def remove_emojis(data): emoj = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) u"\U00002500-\U00002BEF" # chinese char u"\U00002702-\U000027B0" u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" u"\U0001f926-\U0001f937" u"\U00010000-\U0010ffff" u"\u2640-\u2642" u"\u2600-\u2B55" u"\u200d" u"\u23cf" u"\u23e9" u"\u231a" u"\ufe0f" # dingbats u"\u3030" "]+", re.UNICODE) return re.sub(emoj, '', data)
import re result = re.sub('[(\U0001F600-\U0001F92F|\U0001F300-\U0001F5FF|\U0001F680-\U0001F6FF|\U0001F190-\U0001F1FF|\U00002702-\U000027B0|\U0001F926-\U0001FA9F|\u200d|\u2640-\u2642|\u2600-\u2B55|\u23cf|\u23e9|\u231a|\ufe0f)]+','','A quick brown fox jumps over the lazy dog😐🤯')
그런데, 적용을 해도 안되었다.
아차! 하는 생각에 encoding 옵션을 주니, 에러 메시지가 없어졌다.
with open(keyword + '/' + '블로그 본문 내용들.txt', 'a', encoding='utf-8') as f: f.write(body_contents)
때로는 쉽게 생각하는 것이 정답일 때도 있는 듯...
'코딩 연습 > 코딩배우기' 카테고리의 다른 글
selenium으로 네이버 쿠키를 얻고 세션을 유지하는 방법 (2) 2022.01.03 웹 브라우저 페이지를 자동으로 스크롤 해보기 (with 파이썬) (0) 2021.12.28 파이썬 selenium 라이브러리 - find_elements_by_* commands are deprecated. (0) 2021.12.25 크롬 웹드라이버 '시스템에 부착된 장치가 작동하지 않습니다.' 메시지 (0) 2021.12.25 네이버 등 웹 페이지의 쿠키(cookie)를 가져와서 저장하기 (with Python) (0) 2021.12.25