爬一爬糗事百科

  这段时间在学python爬虫,就先拿糗事百科下手,教程是学点击打开链接这个的,但是我学的时候,糗事百科改版了,所以之前的正则表达式就不能用了,要自己写。

  思路还是一样,先用hearders跳过验证,然后用urllib2.Request()和urllib2.urlopen()来获取网页内容,最后用正则式提取所想要的内容。

  我提取的是作者、内容、点赞数和评论数。

  在这里特别说一下我觉得最麻烦的其实是正则匹配,.*?这个可以匹配任何字符,所以没有用的字符都可以交给它,同时,不要忘记后面跟一个特别的字符,不然会贪婪太多的字符。

# -*- coding: utf-8 -*-
__author__ = 'XYlander'


import urllib
import urllib2
import re

class crawler(object):
    def requesturl(self):
        page = 1
        url = 'http://www.qiushibaike.com/hot/page/'+str(page) #URL地址
        user_agent = 'Mozilla/4.0 (compatible;MSIE 5.5;Windows NT)'
        headers = {'User-Agent' : user_agent}
        try :
            request = urllib2.Request(url,headers=headers)
            self._response = urllib2.urlopen(request)
            #print self._response.read()
            print 'get'
        except urllib2.URLError,e:
            if hasattr(e,"code"):
                print e.code
            if hasattr(e,"reason"):
                print e.reason
    def absruct(self):
        content = self._response.read().decode('utf-8')
        pattern = re.compile('<div class="author clearfix">\n<a.*?img.*?h2>(.*?)</h2>.*?</div>.*?<div class="content">.*?<span>(.*?)</span>.*?<div class="stats".*?i class="number">(.*?)</i>.*?i class="number">(.*?)</i>',re.S)
        items = re.findall(pattern,content)
        for item in items:
            #print 'the author is {0},the content is {1},the number of like is {2},the number of comment is {3}'.format(item[0].encode('utf-8'),item[1],item[2],item[3])
            print 'the author is %s,the content is %s,the number of like is%s,the number of comment %s'%(item[0],item[1],item[2],item[3])

if __name__ == '__main__':
    cr = crawler()
    cr.requesturl()
    cr.absruct()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值