Python库详解之网络(2)
昨天试了下用HTMLParser类来解析网页,可发现结果并不理想。不管怎么说,先写下过程,希望后来人能在此基础上解决我所遇到的问题。
写了2套解决方案,当然这2套只能对特定网站有效。我这里主要说明下对BBC主页www.bbc.co.uk和对网易www.163.com的解析。
对于BBC:
这套要简单得多,可能是该网页的编码比较标准吧
import html.parser
import urllib.request
class parseHtml(html.parser.HTMLParser):
def handle_starttag(self, tag, attrs):
print("Encountered a {} start tag".format(tag))
def handle_endtag(self, tag):
print("Encountered a {} end tag".format(tag))
def handle_charref(self,name):
print("charref")
def handle_entityref(self,name):
print("endtiyref")
def handle_data(self,data):
print("data")
def handle_comment(self,data):
print("comment")
def handle_decl(self,decl):
print("decl")
def handle_pi(self,decl):
print("pi")
#从这里开始看起,上面那个继承很简单,全部重载父类函数
#以二进制写的方式存储BBC网页,这是上篇内容(http://blog.csdn.net/xiadasong007/archive/2009/09/03/4516683.aspx),不赘述
file=open("bbc.html",'wb') #it's 'wb',not 'w'
url=urllib.request.urlopen("http://www.bbc.co.uk/")
while(1):
line=url.readline()
if len(line)==0:
break
file.write(line)
#生成一个对象
pht=parseHtml()
#对于这个网站,我使用'utf-8'打开,否则会出错,其他网站可能就不需要,utf-8是UNICODE编码
file=open("bbc.html",encoding='utf-8',mode='r')
#处理网页,feed
while(1):
line=
相关文档:
源代码下载:下载地址在这里
# 037
fileName = ''
while 1:
fileName = raw_input("Input a file name:")
if fileName == 'q':
break
try:
f = file(fileName, 'r')
print 'Opened a file.'
except:
print 'There is no file named', fileName
......
# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
output:
> ......
Python Firewall Win32 (pyfw-win32)
pyfw-win32是一个可用Python脚本开发数据包过滤(防火墙)的模块。底层使用C语言编写的NDIS中间层驱动(NDIS IMD)提供支持,上层提供Python开发接口。可用Python脚本处理所有逻辑问题,而不必关心底层实现,达到快速、灵活开发的目的。
Google 项目托管:
http://code.google.com/p/py ......
学习Python的道路漫漫,光看不练比较无聊。
找了个网页,上面有几道习题,无聊之余拿来练手,还有些乐趣。
是这里:http://www.cnblogs.com/belaliu/archive/2006/11/25/572140.html
注:习题后面贴的代码不一定是最优的。
大部分比较好解决,有点难度的是第4题做去除字符串内的空格的操作。
找了网上的解决方案,有这 ......
怎么找不到第三章的学习笔记了?丢了?
Python的函数没有什么的,可以说,看了《简明Python教程》后,就会写了。
这一章提供的内容也比《简明Python教程》要多一些。比较复杂的是作用域规则,不知道是书没讲清楚还是翻译得不好,比较难懂。钱能的《C++程序教程》关于函数的作用域规则讲得要清楚些,有C++的知识在里面, ......