我正在用 Python 将一些 Unicode 字符串写入 HTML。我这样做的方式是在内部使用 Unicode,并且只在输出时进行编码。所以像这样:
with open(filename, 'w') as f:
f.write(s.encode("utf-8"))
这在我的本地机器上工作正常。但是当它被放到 Travis CI 上时,生成的文件有 ü 代替 ü。有什么想法吗?
这是我的.travis.yml:
language: python
python: 2.7.10
install: pip install -r requirements.txt
script: python main.py -d
deploy:
provider: s3
access_key_id: XXX
secret_access_key:
secure: XXX
bucket: www.my.org
region: us-east-1
skip_cleanup: true
default_text_charset: 'utf-8'
local-dir: output
更新
可以重现该问题的最小 Python 代码如下:
from pyquery import PyQuery as pq
argurl = 'http://hackingdistributed.com/tag/bitcoin/'
d = pq(url=argurl)
authors = []
for elem in d.find("h2.post-title a"):
pubinfo = pq(elem).parent().parent().find(".post-metadata .post-published")
author = pq(pubinfo).find(".post-authors").html().strip()
authors.append(author)
with open('output/test.html', 'w') as f:
f.write(': '.join(authors).encode('utf-8'))
检查 output/test.html 以查看 ü¼。
请您参考如下方法:
这似乎是因为您的浏览器可能错误地读取了该文件。最简单的解决方法是通过将 BOM 标记添加到文件的开头,将其编码为 UTF-8 BOM。
这是写入文件的固定代码:
with open('output/test.html', 'w') as f:
f.write(u'\ufeff'.encode('utf-8')) # BOM marker
f.write(': '.join(authors).encode('utf-8'))
