python爬虫:批量刷新网页

来源:互联网 发布:北航软件学院分数线 编辑:程序博客网 时间:2024/05/19 05:39

版权声明:本文为博主原创文章,未经博主允许不得转载。

说明:
本片文章介绍如何使用python批量刷新网页,以csdn我的博客为例。
分析
首先通过http://blog.csdn.net/cclarence?viewmode=list这个摘要目录得到我所有的博客链接,因为现在的博客较少,所以不用考虑页数的问题,只有一页。http://blog.csdn.net/whiterbear/article/details/44981231这篇文章中声明了为什么用摘要视图而不是目录视图,在实际尝试中也发现目录视图下难以得到结果。得到源代码之后用正则和匹配策略的方式得到所有的博客链接。随后循环访问每一篇博客,可以调整访问次数。大概每次访问页面时间为4.5秒。

# -*- coding:utf-8 -*-import sysimport urllibimport urllib2import rereload(sys)sys.setdefaultencoding('utf-8')# 伪装成浏览器,注意headers必须是一个字典headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36'}# 我们指定url并发送请求req = urllib2.Request(    'http://blog.csdn.net/cclarence?viewmode=list', headers=headers)# 接着服务端响应来自客户端的请求response = urllib2.urlopen(req)lines = ''.join(response.read())#正则表达式得到链接,有些链接不是我们想要的并可能有重复,在下面if语句中判断regex = r'href="(.*?)"'L = []#count用来记数,因为根据此正则规则从源码找出的有重复count = 1 for m in re.findall(regex, lines):    if len(m) == 35 and count % 2 == 1 and "category" not in m and m not in L:        L.append(m)    count = count + 1#开始拼接每一个url并循环访问urlprint "get url:"+'\n'print len(L)for mm in L:    url = 'http://blog.csdn.net/' + mm    print url    headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36'}    #每个url循环5次    for num in range(1,6):        req_url = urllib2.Request(url, headers=headers)        response_url = urllib2.urlopen(req_url)    print "crawling success this url"print "success"

运行结果为:
这里写图片描述

访问量差异(每篇文章多了五次):
这里写图片描述               这里写图片描述

0 0
原创粉丝点击