python第三方库requests和bs4库实例——简单的37行python爬虫刷CSDN博客阅读数

仅供python学习,不用作商业用途

一点私心,为什么我想刷自己的博客呢?因为我觉得我写的博客还是蛮不错的,可以帮很多人少走一些弯路,而低的阅读量在搜索排名中是很不占优的,所以希望我的博客能让更多人受益,刷一点访问量啦,还请原谅。

恰巧前段时间看完了嵩天老师的爬虫基础MOOC,我就思考如何增加爬虫经验,顺便增加一点点我的博客访问量。

运行环境:
Windows 10
pycharm

所需要的python第三方库:requests,bs4安装方法:

pip install requests
pip install bs4
# -*- coding:utf-8 -*-
# 利用爬虫刷CSDN博客阅读数

import requests
from bs4 import BeautifulSoup

# 解析源码
def GetHtmlText(url):
    try:
        r = requests.get(url, timeout = 30)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        return ''

# 查找博文地址并进行一次点击
def Find_Click(soup):
    Divs = soup.find_all('div', {'class': 'article-item-box csdn-tracking-statistics'})
    for Div in Divs:
        ClickUrl = Div.find('h4').find('a')['href']
        # 点一下
        Click = requests.get(ClickUrl, timeout = 30)

def main():
    # 博文页数
    Pages = int(input('Please enter the number of blog pages:'))
    for Page in range(1, Pages + 1):
        print('Page=', Page)
        # 博客地址,这里是我的CSDN博客地址
        url = 'https://blog.csdn.net/qq_44621510/article/list/' + str(Page)
        html = GetHtmlText(url)
        soup = BeautifulSoup(html, 'html.parser')
        Find_Click(soup)

if __name__ == '__main__':
    main()

运行成功后,输入你的博客页数,程序就会自动把所有的博客遍历一遍,即每个博客阅读数加1.

待优化:
1,运行一次程序,每个博客阅读数只加1,然后运行结束,再想增加需要再次运行。
2,点击速度较慢,大概15秒一页(20个)
3,每次重新运行都要输入page数。

猜你喜欢

转载自blog.csdn.net/qq_44621510/article/details/90171944