Otrzymuję kod źródłowy strony internetowej, a kodowanie to cp1252. Chrome wyświetla poprawnie stronę.Jak odszyfrować cp1252, który jest w systemie dziesiętnym? Zamiast x93?
Oto mój kod:
import sys
from urllib.request import urlopen
from bs4 import BeautifulSoup, UnicodeDammit
import re
import codecs
url = "http://www.sec.gov/Archives/edgar/data/1400810/000119312513211026/d515005d10q.htm"
page = urlopen(url).read()
print(page)
# A little preview :
# b'...Regulation S-T (§232.405 of this chapter) during the preceding 12 months (or for such shorter period that the\nregistrant was required to submit and post such files). Yes <FONT STYLE="FONT-FAMILY:WINGDINGS">x</FONT>...'
soup = BeautifulSoup(page, from_encoding="cp1252")
print(str(soup).encode('utf-8'))
# Same preview section as above
# b'...Regulation S-T (\xc2\xa7232.405 of this chapter) during the preceding 12 months (or for such shorter period that the\nregistrant was required to submit and post such files).\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Yes\xc2\xa0\xc2\xa0<font style="FONT-FAMILY:WINGDINGS">x</font>'
W sekcji podglądu, możemy zobaczyć, że
& nbsp \; = \ xc2 \ xa0
& # 167; = \ xc2 \ xa7
& # 120; = X
dla standardu kodowania CP1252, jestem refering http://en.wikipedia.org/wiki/Windows-1252#Code_page_layout i /Lib/encodings/cp1252.py
Gdy używam BeautifulSoup (strona, from_encoding = "CP1252") niektóre znaki są kodowane poprawnie, ale inne nie.
znak | kodowanie dziesiętne | cp1252-> utf-8 kodowanie
"| & # 147; | \ xc2 \ x93 (źle)
"| & # 148; | \ xc2 \ x94 (źle)
X | & # 120; | \ xc2 \ x92 (źle)
§ | & # 167; | \ xc2 \ xa7 (ok)
þ | & # 254;
¨ | & # 168;
"| & # 146; | \ xc2 \ x92 (źle)
- | & # 150;
używam tego kodu, aby uzyskać równoważność:
characters = "’ “ ” X § þ ¨ ' –"
list = characters.split()
for ch in list:
print(ch)
cp1252 = ch.encode('cp1252')
print(cp1252)
decimal = cp1252[0]
special = "&#" + str(decimal)
print(special)
print(ch.encode('utf-8'))
print()
offenders = [120, 146]
for n in offenders:
toHex = hex(n)
print(toHex)
print()
#120
off = b'\x78'
print(off)
buff = off.decode('cp1252')
print(buff)
uni = buff.encode('utf-8')
print(uni)
print()
#146
off = b'\x92'
print(off)
buff = off.decode('cp1252')
print(buff)
uni = buff.encode('utf-8')
print(uni)
print()
wyjście
’
b'\x92'
’
b'\xe2\x80\x99'
“
b'\x93'
“
b'\xe2\x80\x9c'
”
b'\x94'
”
b'\xe2\x80\x9d'
X
b'X'
X
b'X'
§
b'\xa7'
§
b'\xc2\xa7'
þ
b'\xfe'
þ
b'\xc3\xbe'
¨
b'\xa8'
¨
b'\xc2\xa8'
'
b"'"
'
b"'"
–
b'\x96'
–
b'\xe2\x80\x93'
0x78
0x92
b'x'
x
b'x'
b'\x92'
’
b'\xe2\x80\x99'
Niektóre znaki nie powiodło się kopiowania i wklejania do redakcji niczym dziwnym X i dziwne”, więc dodałem jakiś kod, żeby sobie z tym poradzić.
Co mogę zrobić z get \ xe2 \ x80 \ x9d zamiast \ xc2 \ x94 dla "(& # 148;)?
Moja konfiguracja:
Windows 7
terminalowe: CHCP 1252 + Lucida Console czcionki
Python 3.3
BeautifulSoup 4
Czekamy na odpowiedzi