读网页
1. 打印出网页
显示出来的比较乱,尤其是中文没有显示出来。
2. 解决中文问题
[quote]hello.txt
中文显示测试
中文![/quote]
看来直接显示中文没有问题。
3. 尝试decode
搞定!'cp936'是什么?有人说就是指系统里第936号编码格式,也就是GB2312。也有人说就是GBK。Anyway,正常显示出来了。下一步尝试用html.parser — Simple HTML and XHTML parser
4.用html.parser
顾名思义,html.parser就是用来解析HTML文本文件的。是Python标准库之一。
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. 解决中文问题
[quote]hello.txt
中文显示测试
中文![/quote]
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)