# -*- coding: UTF-8 -*-
'''
Created by chenbo on 15/3/14
'''
import urllib2,re
def getpage(url):
f=urllib2.Request(url)
#此时添加header,模拟浏览器访问,否则会报错:HTTPError: HTTP Error 403: Forbidden
f.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5")
#访问请求地址
page = urllib2.urlopen(f)
#读取页面内容
content = page.read()
page.close()
return content
def getInfo(f):
#使用正则匹配数据
# <h3><a href="http://my.oschina.net/u/1585857/blog/386691" target='_blank'>Wireshark分析非标准端口号流量</a></h3>
# <p>Wireshark分析非标准端口号流量 2.2.2 分析非标准端口号流量Wireshark分析非标准端口号流量 应用程序运行使用非标准端口号...</p>
# <div class='date'>大学霸 发布于 1天前</div>
p=re.compile(r'<h3><a href="(.*?)".*?>(.*?)</a>.*?\s*?<p>(.*?)</p>\s*?<div class=\'date\'>(.*?)<')
result=p.findall(f)
#result是一个由4个元素组成的元组组成的列表 [(t1,t2,t3,t4),(t5,t6,67,t8),.......]
'''
如果直接使用以下输出,则无法正常显示中文
for item in result:
for link,title,abstract,publisher in item: #由于含有中文提示ValueError: too many values to unpack
print link
print title
print abstract
print publiser
'''
for item in result:
for i in range(4):
if i==0:
print u"链接地址:",
elif i==1:
print u"标题:",
elif i==2:
print u"摘要:",
else:
print u"发布人、发布时间:",
print item[i].decode("utf-8")
## for link,title,abstract,date in item:
## print link,title.decode("utf-8"),abstract.decode("utf-8"),date
print
if __name__ == '__main__':
url="http://www.oschina.net/blog/more?p=1"
content = getpage(url)
getInfo(content)
转载于:https://my.oschina.net/chenbo/blog/656547