이 URL을 다운로드하고 싶습니다… 그러나 그것은 나에게 오류를주고 있습니다! … 유니 코드 .. (파이썬)

StackOverflow https://stackoverflow.com/questions/1808612

문제

theurl = 'http://bit.ly/6IcCtf/'
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
if unicode == 1:
    #print urlResponse.headers['content-type']
    #encoding=urlResponse.headers['content-type'].split('charset=')[-1]
    #htmlSource = unicode(htmlSource, encoding)
    htmlSource =  htmlSource.encode('utf8')
return htmlSource

유니 코드 부분을 살펴보십시오. 이 두 가지 옵션을 시도했지만 작동하지 않습니다.

htmlSource =  htmlSource.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 370747: ordinal not in range(128)

또한 더 긴 인코딩 방법을 시도 할 때 ...

_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
도움이 되었습니까?

해결책

HTML 데이터는 인터넷에서 나오는 문자열입니다. 이미 인코딩되었습니다 인코딩으로. 인코딩하기 전에 utf-8, 너 먼저 디코딩해야합니다.

파이썬은 암시 적 그것을 해독하려고합니다 (그래서 당신은 UnicodeDecodeError ~ 아니다 UnicodeEncodeError).

문제를 해결할 수 있습니다 바인드 스트링을 디코딩하는 설명 (적절한 인코딩 사용) ~ 전에 그것을 다시 시도하려고합니다 utf-8.

예시:

utf8encoded = htmlSource.decode('some_encoding').encode('utf-8')

올바른 인코딩을 사용하여 페이지가 먼저 인코딩 된 대신 'some_encoding'.

가지다 문자열이 사용하는 인코딩을 알기 전에 해독하기 전에 문자열이 사용됩니다.

다른 팁

디코딩하지 않습니까? htmlSource = htmlSource.decode('utf8')

디코드는 "UTF8 인코딩에서 htmlsource decode"를 의미합니다.

인코딩 "htmlSource를 UTF8 인코딩으로 인코딩"

기존 데이터 (웹 사이트에서 크롤링)를 추출하려면 디코딩해야하며 MySQL에 삽입하면 MySQL DB/Table/Fields Collations에 따라 UTF8로 인코딩해야 할 수도 있습니다.

아마 당신은 원할 것입니다 풀다 UTF8은 아닙니다 인코딩 그것:

htmlSource =  htmlSource.decode('utf8')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top