我使用python + BS4 + pyside代码,请看看下面的代码部分:UnicodeWarning:某些字符不能被解码,并与替换字符被替换
enter code here
#coding:gb2312
import urllib2
import sys
import urllib
import urlparse
import random
import time
from datetime import datetime, timedelta
import socket
from bs4 import BeautifulSoup
import lxml.html
from PySide.QtGui import *
from PySide.QtCore import *
from PySide.QtWebKit import *
def download(self, url, headers, proxy, num_retries, data=None):
print 'Downloading:', url
request = urllib2.Request(url, data, headers or {})
opener = self.opener or urllib2.build_opener()
if proxy:
proxy_params = {urlparse.urlparse(url).scheme: proxy}
opener.add_handler(urllib2.ProxyHandler(proxy_params))
try:
response = opener.open(request)
html = response.read()
code = response.code
except Exception as e:
print 'Download error:', str(e)
html = ''
if hasattr(e, 'code'):
code = e.code
if num_retries > 0 and 500 <= code < 600:
# retry 5XX HTTP errors
return self._get(url, headers, proxy, num_retries-1, data)
else:
code = None
return {'html': html, 'code': code}
def crawling_hdf(openfile):
filename = open(openfile,'r')
namelist = filename.readlines()
app = QApplication(sys.argv)
for name in namelist:
url = "http://so.haodf.com/index/search?type=doctor&kw="+ urllib.quote(name)
#get doctor's home page
D = Downloader(delay=DEFAULT_DELAY, user_agent=DEFAULT_AGENT, proxies=None, num_retries=DEFAULT_RETRIES, cache=None)
html = D(url)
soup = BeautifulSoup(html)
tr = soup.find(attrs={'class':'docInfo'})
td = tr.find(attrs={'class':'docName font_16'}).get('href')
print td
#get doctor's detail information page
loadPage_bs4(td)
filename.close()
if __name__ == '__main__':
crawling_hdf("name_list.txt")
我运行后程序,有显示华林消息:
警告(从警告模块): 文件 “C:\ Python27 \ LIB \站点包\ BS4 \ dammit.py”,行231 “中的某些字符不能解码,并且是“ UnicodeWarning:某些字符无法解码,并被替换与替换字符。
我用打印STR(HTML),发现在每日新闻所有中国语言都是乱码。
我曾尝试使用在本网站中搜索的“解码或编码”和“gzip”解决方案,但它在我的情况下不起作用。
非常感谢您的帮助!
“没有直接转换” - 那么,你的意思是*在Python *中? GBK没有什么特别之处,它只是另一种[常规编码](https://en.wikipedia.org/wiki/GBK)。另外:UTF8仅仅是一个存储系统(对于Unicode),所以即使没有“直接”转换,你最好用它的专有名称来调用它,并将UTF8放在这里。 – usr2564301
我不确定你的意思。我对这个问题的理解是,有一个gbk编码的页面,dammit.py无法转换为utf-8。我正在给出一个我见过的使用latin-1作为“翻译器”的解决方法。鉴于上下文,我会说“在Python中”是一个给定的。 FWIW,如果在这里有更好的方式从a到b,我完全赞成! – jinksPadlock
如果你找到的答案有一个可接受的答案,那么这个问题将会是重复的......但是,评论“拉丁-1绕行令人震惊”应该告诉你一些事情。 – usr2564301