我正在尝试下载数百个韩文页面,如下所示:
http://homeplusexpress.com/store/store_view.asp?cd_express=3
对于每个页面,我想使用正则表达式来提取“地址”字段,在上面的页面中如下所示:
*주소 : 서울시 광진구 구의1동 236-53
所以我这样做:
>>> import requests
>>> resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
>>> resp.encoding
'ISO-8859-1'
>>> # I wonder why it's ISO-8859-1, since I thought that is for Latin text (Latin-1).
>>> html = resp.text
>>> type(html)
<type 'unicode'>
>>> html
(outputs a long string that contains a lot of characters like \xc3\xb7\xaf\xbd\xba \xc0\xcd\xbd\xba\xc7\xc1\xb7\xb9\)
然后我写了一个脚本。我在 .py 文件上设置 # -*-coding: utf-8 -*-
并输入:
address = re.search('주소', html)
但是,re.search
返回None
。我尝试了在正则表达式字符串上使用和不使用 u
前缀。
通常我可以通过调用 .encode
或 .decode
来解决此类问题,但我尝试了一些方法,但遇到了困难。关于我所缺少的内容有什么指示吗?
最佳答案
根据html文档头中的标签:
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
网页使用euc-kr编码。
我写了这段代码:
# -*- coding: euc-kr -*-
import re
import requests
resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
html = resp.text
address = re.search('주소', html)
print address
然后我使用 euc-kr 编码将其保存在 gedit 中。
我有一场比赛。
但实际上还有更好的解决方案!您可以保留文件的 utf-8 编码。
# -*- coding: utf-8 -*-
import re
import requests
resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
resp.encoding = 'euc-kr'
# we need to specify what the encoding is because the
# requests library couldn't detect it correctly
html = resp.text
# now the html variable contains a utf-8 encoded unicode instance
print type(html)
# we use the re.search functions with unicode strings
address = re.search(u'주소', html)
print address
关于python - unicode 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23573430/