python爬取oschina博客列表

# -*- 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值