我正在获取网页的源代码,编码为 cp1252。Chrome 可以正确显示页面。
这是我的代码:
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>'
从预览部分,我们可以看到
\; = \xc2\xa0
§ = \xc2\xa7
x = x
对于 cp1252 编码标准,我指的是 http://en.wikipedia.org/wiki/Windows-1252#Code_page_layout 和 /Lib/encodings/cp1252.py
当我使用 BeautifulSoup(page, from_encoding="cp1252") 时,一些字符被正确编码,而另一些则不是。
性格 | 十进制编码 | cp1252->utf-8 编码
“| | \xc2\x93(错误)
” | | \xc2\x94(错误)
X | x | \xc2\x92(错误)
§ | § | \xc2\xa7 (好的)
þ | þ
¨ | ¨
' | | \xc2\x92 (错误)
– |
我使用此代码来获得等价:
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()
输出
’
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'
有些字符无法复制粘贴到编辑器中,比如奇怪的 X 和奇怪的 ',所以我添加了一些代码来处理这个问题。
我可以做什么来获取 \xe2\x80\x9d 而不是 \xc2\x94 for ” ()?
我的设置:
Windows 7
终端:chcp 1252 + Lucida 控制台字体
Python 3.3
BeautifulSoup 4
期待您的回答