博客访问量v1.0 - 入门级爬虫,Python练手必备

见一帖子问:写了几篇CSDN博文,发现阅读数没有提高,怎么办?
有人答:雇水军刷。
对于程序猿而言,雇水军显得“有辱身份”。刚好本屌正在研究Python,正所谓“实践出真知”,于是乎拿自己博客来练练手。
(PS: 假的访问量并没有什么卵用)

思路

Created with Raphaël 2.1.2 开始 主程序 请求博客 解析文章链接 请求文章 挂起N秒 yes no

实现

  • urllib.request:用于发送HTTP请求
  • BeautifulSoup:用于从HTML或XML文件中提取数据
# -*-coding:utf-8-*-
"""
博客访问量
@version 1.0
@requires Python 3.6.4
@author 范围兄 <ambit_tsai@qq.com>
"""
from urllib import request
from bs4 import BeautifulSoup
from time import sleep

# 博客
BLOG = 'ambit_tsai'
# 爬取间隔
CRAWL_INTERVAL = 40

def access_article(soup):
    print('>>访问文章')
    tags = soup.select('#mainBox h4.text-truncate > a')
    for tag in tags:
        href = tag['href']
        print('*', href[-25:], tag.contents[2].strip())
        try:
            res = request.urlopen(href)
        except Exception as ex:
            print('!', ex)
            return

def crawl_blog(blog):
    print('>>爬取博客:', blog)
    url = 'https://blog.csdn.net/' + blog
    print('*', url)
    res = None
    try:
        res = request.urlopen(url)
    except Exception as ex:
        print('!', ex)
        return
    if res.status != 200:
        print('!', res.status, 'URL访问失败')
        return
    soup = BeautifulSoup(res.read().decode())
    access_article(soup)    # 访问列表页的文章

# 开始爬取
while 1:
    print('=========================')
    crawl_blog(BLOG)
    print('>>挂起', CRAWL_INTERVAL, '秒')
    sleep(CRAWL_INTERVAL)

其他

这个版本只实现了基本功能,技术含量偏低,下一版将加入伪装功能,让爬虫能够模拟正常行为。正所谓,不想“以假乱真”的爬虫,不是好的爬虫。

博客访问量v2.0 - “伪装者”版爬虫

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值