版权声明:本文为博主原创文章,未经博主允许不得转载。
说明:
本片文章介绍如何使用python批量刷新网页,以csdn我的博客为例。
分析
首先通过http://blog.csdn.net/cclarence?viewmode=list这个摘要目录得到我所有的博客链接,因为现在的博客较少,所以不用考虑页数的问题,只有一页。http://blog.csdn.net/whiterbear/article/details/44981231这篇文章中声明了为什么用摘要视图而不是目录视图,在实际尝试中也发现目录视图下难以得到结果。得到源代码之后用正则和匹配策略的方式得到所有的博客链接。随后循环访问每一篇博客,可以调整访问次数。大概每次访问页面时间为4.5秒。
# -*- coding:utf-8 -*-
import sys
import urllib
import urllib2
import re
reload(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并循环访问url
print "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"
运行结果为:
访问量差异(每篇文章多了五次):