Python爬虫入门教程 17-100 博客抓取数据

写在前面

写了一段时间的博客了,忽然间忘记了,其实博客频道的博客也是可以抓取的,所以我干了.....



其实这事情挺简单的,打开CSDN博客首页,他不是有个最新文章么,这个里面都是最新发布的文章。

在这里插入图片描述

打开F12抓取一下数据API,很容易就获取到了他的接口

在这里插入图片描述

提取链接长成这个样子

https://blog.csdn.net/api/articles?type=more&category=newarticles&shown_offset=1540381234000000

发现博客最新文章是一个瀑布流页面,不断下拉,只有一个参数shown_offset 在变化,按照我多年的行医经验,这个参数是个时间戳,而且肯定是上一次数据最后一条的时间戳。

基于这个理论,看一下数据,咦,猜对了~~~~~

博客返回的数据看一下,是否对味

在这里插入图片描述

撸代码

这个步骤就非常简单了,就是通过requests去抓取这个链接就好了

import requests
import pymongo
import time

START_URL = "https://www.csdn.net/api/articles?type=more&category=newarticles&shown_offset={}"
HEADERS = {
    "Accept":"application/json",
    "Host":"www.csdn.net",
    "Referer":"https://www.csdn.net/nav/newarticles",
    "User-Agent":"你自己的浏览器配置",
    "X-Requested-With":"XMLHttpRequest"
}
def get_url(url):
    try:
        res = requests.get(url,
                           headers=HEADERS,
                           timeout=3)

        articles = res.json()
        if articles["status"]:
            need_data = articles["articles"]
            if need_data:
                collection.insert_many(need_data)  # 数据插入
                print("成功插入{}条数据".format(len(need_data)))
            last_shown_offset = articles["shown_offset"]  # 获取最后一条数据的时间戳
            if last_shown_offset:
                time.sleep(1)
                get_url(START_URL.format(last_shown_offset))
    except Exception as e:
        print(e)
        print("系统暂停60s,当前出问题的是{}".format(url))

        time.sleep(60) # 出问题之后,停止60s,继续抓取
        get_url(url)

数据获取到了,当然要象征性的保存一下,mongo数据库的操作在上一篇文章,你可以去翻翻。

在这里插入图片描述

猜你喜欢

转载自www.cnblogs.com/happymeng/p/10212455.html