美文网首页
python 爬取博客访问量并且统计数据成图

python 爬取博客访问量并且统计数据成图

作者: a0f39b0b2030 | 来源:发表于2018-10-31 18:21 被阅读29次

爬取自己博客访问量

环境

Python3.6

Windows10

第三方库(下面)

用到的第三方库

requests : 访问博客用的专用,特别好用的库

BeautifulSoup : 解析返回的html节点用的库

此模块的思路

有了上面的两个库就好说了,先用requests去请求对应的博客网址,在用BeautifulSoup解析html节点,用bs里的方法进行匹配html节点,抓出想要的数据,最后记录每天的访问量和日期,输出到txt文档中。

而用浏览器自带的F12找对应的访问量的节点很好找。如下图:

代码实现

这里不多说,代码上有注释,很详细了

#coding = utf-8

import requests

from bs4 import BeautifulSoup as bs

import re

import time

访问我的博客

def spider(url, headers):

r = requests.get(url=url, headers=headers)

html = r.text

# 解析html代码

soup = bs(html, ‘lxml’)

ul = soup.find(name=‘ul’, attrs={‘id’: ‘blog_rank’})

# 获取ul下的第一个li节点,正则表达式需要字符串,所以转化一下

li = str(ul.find_next(‘li’))

numbers = re.findall(r’span>(.+?)次

# print(numbers)

# 获取当前年月日

date = time.strftime("%Y-%m-%d", time.localtime())

# 拼接日期

numbers.append(date)

text_save(numbers, ‘visitorNumber.txt’)

print(‘成功执行!’)

文件存储

def text_save(content, filename, mode=‘a’):

# Try to save a list variable in txt file.

file = open(filename, mode)

for i in range(len(content)):

# 如果索引为最后一位,去掉空格且拼上换行符,否则剩下的后面拼接逗号

if i == len(content) - 1:

number = (content[i]) + ‘\n’

else:

number = str(content[i]) + ‘,’

file.write(number)

file.close()

if name == ‘main’:

url = "http://blog.csdn.net/s740556472/article"

headers = {

    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

    'Accept-Encoding': 'gzip, deflate, sdch',

    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',

    'Cache-Control': 'max-age=0',

    'Connection': 'keep-alive',

    'Host': 'blog.csdn.net',

    'Upgrade-Insecure-Requests': '1',

    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'

}

spider(url, headers)

1

2

3

4

5

6

7

8

9

10

11

12

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

然后代码执行后如下图:

打开看看生成的格式:

这样此模块就算完成了代码上的,但是我觉得每天手动去执行好麻烦,于是想到了可以用windows自带的定时器(也就是任务计划)去执行脚本。

windows每天定时执行脚本

这里说的定时器就是Windows下的任务计划,当时遇到的坑正好总结一下,因为Windows10的定时器去执行脚本当时试了好多遍,都是没有成功,后来通过自己的观察发现是定时器调用路径的坑。。废话不多说了,直接上图了。

Windows键+R 调出此窗口,输入compmgmt.msc (调用的是计算机管理)

2.点击下面的框,创建一个基本任务

3.开始配置任务

4.任务计划的问题

重点:至此配置完成了执行计划,但是!!!!!如果你发现你定时之后Windows并没有执行你的脚本,那么一定是你的批处理文件写的有问题,也就是.bat的问题。

刚开始LZ也是一脸懵逼, 为什么就执行不了呢!后来决定用在.bat中添加pause;试试,让cmd执行完停止在这里看看。如下图:

这里有个test.bat是用来任务计划测试用的Windows脚本,还有一个是helloworld的脚本。

test.bat如下图所示:

python3 helloWorld.py

#这行代码可以让Windows调用

#cmd的窗口暂停住,不会自动消失

pause;

1

2

3

4

当到时间自动执行后,发现:

冷练车系统开发找上海捌跃网络科技有限公司

Windows调用的时候,默认cmd路径是在system32下,所以。。。

我们需要将我们的批处理文件改动一下。

1

2

最终我执行抓取博客的.bat文件如下:

先cd到脚本的路径下,再去执行既可成功运行:

冷练车

至此,第一个模块全部完成。

读取txt数据生成访问量与日期图

这里就坐等了两个月的数据,每天都会自己执行一下,然后继续上代码

代码实现

代码不详讲,有注释。

#coding=utf-8

import matplotlib.pyplot as plt

import matplotlib.dates as mdates

import datetime

import decimal

#根据数据动态画图

def drawBydata():

#读取输出的txt文档

(recordDate,y) = readData(‘visitorNumber.txt’)

#获取记录的日期列表范围(0,)

x = range(len(recordDate))

# plt.figure() 开始画图,r:红色

#http://www.360doc.com/content/15/0113/23/16740871_440559122.shtml

plt.plot(x,y,‘ro-’)

#rotation,x轴字体旋转的角度

plt.xticks(x, recordDate,rotation=70)

plt.margins(0.08)

plt.subplots_adjust(bottom=0.15)

#设置x轴的名字

plt.xlabel(“Date”)

plt.ylabel(“Visitors”)

#图的标题

plt.title(“My blog visit analysis”)

plt.show()

print(‘执行成功!’)

#读取数据

def readData(fileName):

#以只读文件打开

inFile = open(fileName,‘r’)

#定义第一列数据为博客访问量

visitors = []

#第二列数据为日期

recordDate = []

#遍历文件每一行

for line in inFile:

#逗号分隔

trainingSet = line.split(’,’)

#将第一列和第二列数据拼入对应的列表中

visitors.append(trainingSet[0])

recordDate.append(trainingSet[1])

inFile.close()

return (recordDate,visitors)

if name == ‘main’:

drawBydata()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

执行后的效果图

如下图,有木有很清晰呢- -哈哈哈!

原文:https://blog.csdn.net/s740556472/article/details/78239204

相关文章

网友评论

      本文标题:python 爬取博客访问量并且统计数据成图

      本文链接:https://www.haomeiwen.com/subject/ruxztqtx.html