编程悬崖,回头是岸 ——Python:转码并保存到本地
抓取了x事百科的页面
#coding:utf-8
import urllib
import urllib2
import sys
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
这里是摘取页面
#get html
def getHtml(url):
#at first,you need to import urllib&urllib2
response = None
requset = None
html_body = None
#add header 这里是添加头信息
headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
#catch exception
try:
#get html body 获取网页
requset = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(requset)
html_body = response.read()
if not html_body:
html_body = 'error,please check your code!'
return html_body
except urllib2.HTTPError,e: #对错误的捕获
print e.code
except urllib2.URLError,e:
#httperror是urlerror子类,所以url要放后面
print e.reason
#if hasattr(e,'code'):
# print 'Error code:',e.code
#elif hasattr(e,'reason'):
# print 'Reason:',e.code
finally:
#close steam
if response:
response.close()
这个是转码,网页的大多是utf8,我用的是cmd,所以是gbk的,要转一下,不然会乱码
#html:utf-8,cmd-gbk,need to translate
def decodeStr(str):
#at first,you need to import sys
type = sys.getfilesystemencoding()
return str.decode('utf-8').encode(type)
这个是重点,继承了HTMLParser,这个是自带的解析网页的,里面有好几个方法可以重写
class MyHTMLParser(HTMLParser):
def _init_(self):
HTMLParser._init_(self)
#这个是获取tag的
#def handle_starttag(self,tag,attrs):
#这个是获取标签内容的
def handle_data(self, data):
if len(data) >8:
#因为刚学这个,还不知道怎么过滤,就把字符长度大于8的过滤掉
f = file('getHtml.txt','a')
#读取你要输出的目标文件,如果没有则创建,a是参数,表示内容追加,还有w等可选
f.write(data)
f.close()
print(decodeStr(data))
#这里在输出到控制台的时候做了转码
def main():
#get html
print "====start----------------"
html = getHtml("http://www.qiushibaike.com/")
parser = MyHTMLParser()
parser.feed(html) #把上面获取的页面内容放到解析器去解析
print "====end----------------"
#run py
main()
本来想把输出弄好看点,然而好心急好心急想看西部世界,所以…………………