北风留影 发表于 2017-5-6 08:00:44

用Python 3000 写点有用的东西

读网页
1. 打印出网页

import urllib.request
url = 'http://www.google.cn/'
f = urllib.request.urlopen(url)
try:
for line in f.readlines():
print(line)
finally:
f.close()

显示出来的比较乱,尤其是中文没有显示出来。
2. 解决中文问题
引用
hello.txt
中文显示测试
中文!


f = open("c:/hello.txt")
try:
for line in f:
print(line)
finally:
f.close()

看来直接显示中文没有问题。
3. 尝试decode

import urllib.request
url = 'http://www.google.cn/'
f = urllib.request.urlopen(url)
try:
for line in f.readlines():
print(line.decode('cp936'))
finally:
f.close()

搞定!'cp936'是什么?有人说就是指系统里第936号编码格式,也就是GB2312。也有人说就是GBK。Anyway,正常显示出来了。下一步尝试用html.parser — Simple HTML and XHTML parser
4.用html.parser
顾名思义,html.parser就是用来解析HTML文本文件的。是Python标准库之一。

import urllib.request
from html.parser import HTMLParser
url = 'http://www.google.cn/'
f = urllib.request.urlopen(url)
source = f.read().decode("cp936")
parser = HTMLParser()
parser.feed(source)
页: [1]
查看完整版本: 用Python 3000 写点有用的东西