我想用 Python 抓取网站的内容。像这样:
Apple’s stock continued to dominate the news over the weekend, with Barron’s placing it on the top of its favorite 2013 stock list.
但是以错误结果打印它们:
Apple âs stock continued to dominate the news over the weekend, with Barronâs placing it on the top of its favorite 2013 stock list.
无法显示符号“'”,这是我的代码:
#-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import urllib
from lxml import *
import urllib
import lxml.html as HTML
url = "http://www.forbes.com/sites/panosmourdoukoutas/2012/12/09/apple-tops-barrons- 10-favorite-stocks-for-2013/?partner=yahootix"
sock = urllib.urlopen(url)
htmlSource = sock.read()
sock.close()
root = HTML.document_fromstring(htmlSource)
contents = ' '.join([x.strip() for x in root.xpath("//div[@class='body']/descendant::text()")])
print contents
f = open('C:/Users/yinyao/Desktop/Python Code/data.txt','w')
f.write(contents)
f.close()
但是设置之后,printf的功能就没有用了。为什么?我该怎么办?我用的是Windows,默认的编码方式是gbk。