我正在尝试使用此代码抓取网站

    #!/usr/bin/python
    #coding = utf-8
    import urllib, urllib2
    req = urllib2.Request(‘http://some website’)
    req.add_header('User-agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
    f = urllib2.urlopen(req)
    body = f.read()
    f.close()


这是read()方法返回的文档的一部分

    T\u00f3m l\u01b0\u1ee3c di\u1ec5n ti\u1ebfn Th\u01b0\u1ee3ng H\u1ed9i \u0110\u1ed3ng Gi\u00e1m M\u1ee5c v\u1ec1 Gia \u0110\u00ecnh\


我如何更改上面的代码以获得这样的结果?

    Tóm lược diễn tiến Thượng Hội Đồng Giám Mục về Gia Đình


谢谢。

我的问题通过使用mata的建议得以解决。这里的代码对我有用。谢谢大家的帮助,尤其是mata。

 #!/usr/bin/python
#coding = utf-8
import urllib, urllib2
req = urllib2.Request(‘http://some website’)
req.add_header('User-agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
f = urllib2.urlopen(req)
body = f.read().decode('unicode-escape').encode('utf-8')
f.close()

最佳答案

您需要检测页面的编码并将其解码,请尝试使用此lib进行编码检测http://github.com/chardet/chardet,其使用帮助和示例位于http://chardet.readthedocs.org/en/latest/usage.html

pip install chardet


然后用它

import urllib, urllib2
import chardet  #<- import this lib

req = urllib2.Request(‘http://some website’)
req.add_header('User-agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
f = urllib2.urlopen(req)
body = f.read()
f.close()

code = chardet.detect(body)           #<- detect the encoding
body = body.decode(code['encoding'])  #<- decode

关于python - Python-使用Unicode抓取网站,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35433097/

10-11 22:03
查看更多