urlfetch.fetch에서 얻은 콘텐츠의 문자 코드

urlfetch.fetch(url) 로 GET한 응답을 .content 그러면 문자 깨져서 일본어로 스크래핑할 수 없다. 그럴 때 어떻게 할까?
  • content의 문자 코드를 식별한다.
  • urlfeth.fetch의 headers를 지정한다.
  • 유니코드로 decode한다.

  • 문자 코드 식별



    Chrome에서 URL을 열고 Console -> Networks -> Response Header에서 Content-Type을 확인합니다.


    headers 지정



    Content-Type을 그대로 copipe (당연히, 따옴표는 스스로 넣는다). 위의 경우의 문자 코드는 EUC-JP였다.
    import urlfetch
    
    response = urlfetch.fetch(
        url=url,
        headers={'Content-Type': 'text/html; charset=EUC-JP'})
    

    decode하다



    이 경우 response.content의 문자 코드는 EUC-JP이므로 유니 코드로 디코딩하면 스크래핑이 잘됩니다.
    raw_html = response.content  # このままだとEUC-JP
    raw_html = response.content.decode('euc-jp')  # これでunicodeになる。
    

    Encode, Decode에 대해 마침내 이해했습니다.


    .encode , .decode 의 인수에 unicode 가 나오지 않는다. 즉, 문자 코드는 unicode를 중계해 변환하게 된다(라고 하는 것으로 해 이해했다).

    encode는 unicode를 인수의 문자 코드로 한다.
    유니 코드 -> utf-8 : text.encode('utf-8')유니 코드 -> euc-jp : text.encode('euc-jp')
    decode는 인수의 문자 코드를 unicode로 한다.
    utf-8 -> unicode : text.decode('utf-8')euc-jp -> unicode : text.decode('euc-jp')
    인코딩하면 str('hogehoge')로, 디코딩하면 unicode(u'hogehoge')로 문자열 조작하면 된다.

    참고



    파이썬에서 일본어 문자열 (유니 코드와 UTF-8, Shift-JIS, EUC-JP 등의 상호 변환)

    좋은 웹페이지 즐겨찾기