2015-01-23 3 views
1

파이썬의 urllib.request API를 사용하여 일부 웹 페이지를 크롤링하고 새 파일에 읽은 행을 저장했습니다. 내가 저장 한 파일을 열 때UTF-8 코드를 파이썬의 기호 문자로 변환하는 방법

 f = open(docId + ".html", "w+") 
     with urllib.request.urlopen('http://stackoverflow.com') as u: 
       s = u.read() 
       f.write(str(s)) 

는하지만, 원래는 원래의 페이지에서 화살표 상징 같은 \ XE2 \ 86 \ X90 많은 문자열을 참조하십시오. 심볼의 UTF-8 코드 인 것 같지만 코드를 심볼로 다시 변환하려면 어떻게해야합니까?

+0

기호로 무엇을 의미하는지 모르므로 'unicode()'함수를 사용해보십시오. –

답변

2

귀하의 코드가 파손 참조 : u.read() 반환 bytes 개체를. 그대로

>>> str(b'\xe2\x86\x90') 
"b'\\xe2\\x86\\x90'" 

를 어느 디스크에 바이트를 저장 :

import urllib.request 

urllib.request.urlretrieve('http://stackoverflow.com', 'so.html') 
당신이 그것을 원하지 않아요 - str(bytes_object)는 오브젝트의 캐릭터 표현을 (어떻게 보이는지 바이트 문자)를 반환

또는 바이너리 모드로 파일을 엽니 다 'wb'를 수동으로 저장 :

import shutil 
from urllib.request import urlopen 

with urlopen('http://stackoverflow.com') as u, open('so.html', 'wb') as file: 
    shutil.copyfileobj(u, file) 

또는 유니 코드 바이트로 변환 및 저장 원하는 인코딩을 사용하여 디스크에 저장하십시오.

import io 
import shutil 
from urllib.request import urlopen 

with urlopen('http://stackoverflow.com') as u, \ 
    open('so.html', 'w', encoding='utf-8', newline='') as file, \ 
    io.TextIOWrapper(u, encoding=u.headers.get_content_charset('utf-8'), newline='') as t: 
    shutil.copyfileobj(t, file) 
1

시도 :

import urllib2, io 

with io.open("test.html", "w", encoding='utf8') as fout: 
    s = urllib2.urlopen('http://stackoverflow.com').read() 
    s = s.decode('utf8', 'ignore') # or s.decode('utf8', 'replace') 
    fout.write(s) 

https://docs.python.org/2/howto/unicode.html

관련 문제