أنا فقط أريد تحميل هذا الرابط...لكنه يعطيني خطأ!...unicode..(بايثون)

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

يرجى إلقاء نظرة على unicode جزء.لقد حاولت تلك خيارين...ولكن لا يعمل.

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, ، يجب فك الشفرة الأولى.

بيثون هو implicity محاولة فك ذلك (وهذا هو السبب يمكنك الحصول على UnicodeDecodeError لا UnicodeEncodeError).

يمكنك حل المشكلة عن طريق explicity فك التشفير الخاص بك bytestring (باستخدام ترميز) قبل يحاول reencode إلى utf-8.

على سبيل المثال:

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

استخدام الترميز الصحيح الصفحة المشفرة في المقام الأول بدلا من 'some_encoding'.

لك لديك أن تعرف أي ترميز سلسلة يستخدم قبل أن تتمكن من فك ذلك.

نصائح أخرى

لا حله ؟ htmlSource = htmlSource.decode('utf8')

فك يعني "فك htmlSource من ترميز utf8"

ترميز يعني "ترميز htmlSource إلى ترميز utf8"

منذ كنت استخراج البيانات الموجودة (الزحف من الموقع), تحتاج إلى فك ذلك, و عندما تضاف إلى الخلية ، قد تحتاج إلى ترميز utf8 وفقا mysql db/الجدول/حقول الترتيب.

ربما كنت ترغب في فك Utf8 لا ترميز ذلك:

htmlSource =  htmlSource.decode('utf8')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top