Scrapy爬取博客园精华区内容

程序爬取目标

获取博客园精华区文章的标题、标题链接、作者、作者博客主页链接、摘要、发布时间、评论数、阅读数和推荐数,并存储到MongoDB中。

程序环境

  • 已安装scrapy
  • 已安装MongoDB

创建工程

scrapy startproject cnblogs

在命令提示符中执行上述命令后,会建立一个名为cnblogs的文件夹。

创建爬虫文件

cd cnblogs
scrapy genspider cn cnblogs.com

执行上述命令后,会在cnblogs\spiders\下新建一个名为cn.py的爬虫文件,cnblogs.com允许爬取的域名

编写items.py文件

定义需要爬取的内容。

import scrapy

class CnblogsItem(scrapy.Item):
    # define the fields for your item here like:
    post_author = scrapy.Field()    #发布作者
    author_link = scrapy.Field()    #作者博客主页链接
    post_date = scrapy.Field()      #发布时间
    digg_num = scrapy.Field()       #推荐数
    title = scrapy.Field()          #标题
    title_link = scrapy.Field()     #标题链接
    item_summary = scrapy.Field()   #摘要
    comment_num = scrapy.Field()    #评论数
    view_num = scrapy.Field()       #阅读数

编写爬虫文件cn.py

import scrapy
from cnblogs.items import CnblogsItem

class CnSpider(scrapy.Spider):
    name = ‘cn‘
    allowed_domains = [‘cnblogs.com‘]
    start_urls = [‘https://www.cnblogs.com/pick/‘]

    def parse(self, response):
        div_list = response.xpath("//div[@id=‘post_list‘]/div")
        for div in div_list:
            item = CnblogsItem()
            item["post_author"] = div.xpath(".//div[@class=‘post_item_foot‘]/a/text()").extract_first()
            item["author_link"] = div.xpath(".//div[@class=‘post_item_foot‘]/a/@href").extract_first()
            item["post_date"] = div.xpath(".//div[@class=‘post_item_foot‘]/text()").extract()
            item["comment_num"] = div.xpath(".//span[@class=‘article_comment‘]/a/text()").extract_first()
            item["view_num"] = div.xpath(".//span[@class=‘article_view‘]/a/text()").extract_first()
            item["title"] = div.xpath(".//h3/a/text()").extract_first()
            item["title_link"] = div.xpath(".//h3/a/@href").extract_first()
            item["item_summary"] = div.xpath(".//p[@class=‘post_item_summary‘]/text()").extract()
            item["digg_num"] = div.xpath(".//span[@class=‘diggnum‘]/text()").extract_first()
            yield item

        next_url = response.xpath(".//a[text()=‘Next >‘]/@href").extract_first()
        if next_url is not None:
            next_url = "https://www.cnblogs.com" + next_url
            yield scrapy.Request(
                next_url,
                callback=self.parse
            )

编写pipelines.py文件

对抓取到的数据进行简单处理,去除无效的字符串,并保存到MongoDB中。

from pymongo import MongoClient
import re

client = MongoClient()
collection = client["test"]["cnblogs"]

class CnblogsPipeline(object):
    def process_item(self, item, spider):
        item["post_date"] = self.process_string_list(item["post_date"])
        item["comment_num"] = self.process_string(item["comment_num"])
        item["item_summary"] = self.process_string_list(item["item_summary"])
        print(item)
        collection.insert(dict(item))
        return item

    def process_string(self,content_string):
        if content_string is not None:
            content_string = re.sub(" |\s","",content_string)
        return content_string

    def process_string_list(self,string_list):
        if string_list is not None:
            string_list = [re.sub(" |\s","",i) for i in string_list]
            string_list = [i for i in string_list if len(i) > 0][0]
        return string_list

修改settings.py文件

添加USER_AGENT

USER_AGENT = ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36‘

启用pipelines

ITEM_PIPELINES = {
   ‘cnblogs.pipelines.CnblogsPipeline‘: 300,
}

运行程序

执行下面的命令,开始运行程序。

scrapy crawl cn

程序运行结果

程序运行结束后,MongoDB中的数据如下图所示,采用的可视化工具是Robo 3T



感谢大家的阅读,如果文中有不正确的地方,希望大家指出,我会积极地学习、改正。

再次感谢您耐心的读完本篇文章。

原文地址:https://www.cnblogs.com/dblsha/p/10046683.html

时间: 2024-07-31 12:50:33

Scrapy爬取博客园精华区内容的相关文章

Python爬虫爬取博客园并保存

Python爬虫爬取博客园并保存        爬取博客园指定用户的文章修饰后全部保存到本地 首先定义爬取的模块文件: crawlers_main.py 执行入口 url_manager.py url管理器 download_manager.py 下载模块 parser_manager.py html解析器(解析html需要利用的内容) output_manager.py 输出html网页全部内容文件(包括css,png,js等) crawlers_main.py 执行入口 1 # coding

java爬虫爬取博客园数据

网络爬虫 编辑 网络爬虫(又称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕虫. 网络爬虫按照系统结构和实现技术,大致可以分为以下几种类型:通用网络爬虫(General Purpose Web Crawler).聚焦网络爬虫(Focused Web Crawler).增量式网络爬虫(Incremental Web Crawler).深层网络爬虫(Deep We

webmagic爬取博客园所有文章

最近学习了下webmagic,学webmagic是因为想折腾下爬虫,但是自己学java的,又不想太费功夫,所以webmagic是比较好的选择了. 写了几个demo,源码流程大致看了一遍.想着把博客园的文章列表爬下来吧. 首页显示的就是第一页文章的列表, 但是翻页按钮不是链接,而是动态的地址: 实际请求的地址及参数: 针对这个动态页面的情况,有两种解决方案: 1. webmagic模拟post请求,获取返回页面. 1 public class CnblogsSpider implements Pa

Python+webdriver爬取博客园“我的闪存”并保存到本地

前篇 用webdriver+phantomjs实现无浏览器的自动化过程 本篇 想法与实现 我想要将博客园“我的闪存”部分内容爬取备份到本地文件,用到了WebDriver和Phantomjs的无界面浏览器.对于xpath的获取与校验需要用到firefox浏览器,安装firebug和firepath插件.代码如下: # -*- coding: utf-8 -*- import os,time from selenium import webdriver from selenium.webdriver

Python - 爬取博客园某一目录下的随笔 - 保存为docx

1 #coding:utf-8 2 import requests 3 from bs4 import BeautifulSoup 4 import MySQLdb 5 6 7 def get_html(url): 8 ''' 9 获取页面HTML源码,并返回 10 ''' 11 html = requests.get(url) 12 content = html.text.encode('utf-8') 13 return content 14 15 def get_blog_html_lis

nodejs爬取博客园的博文

其实写这篇文章,我是很忐忑的,因为爬取的内容就是博客园的,万一哪个顽皮的小伙伴拿去干坏事,我岂不成共犯了? 好了,进入主题. 首先,爬虫需要用到的模块有: express ejs superagent (nodejs里一个非常方便的客户端请求代理模块) cheerio (nodejs版的jQuery) 前台布局使用bootstrap 分页插件使用 twbsPagination.js 完整的爬虫代码,在我的github中可以下载.主要的逻辑代码在 router.js 中. 1. 爬取某个栏目第1页

爬虫实战【1】使用python爬取博客园的某一篇文章

第一次实战,我们以博客园为例. Cnblog是典型的静态网页,通过查看博文的源代码,可以看出很少js代码,连css代码也比较简单,很适合爬虫初学者来练习. 博客园的栗子,我们的目标是获取某个博主的所有博文,今天先将第一步. 第一步:已知某一篇文章的url,如何获取正文? 举个栗子,我们参考'农民伯伯'的博客文章吧,哈哈.他是我关注的一个博主. http://www.cnblogs.com/over140/p/4440137.html 这是他的一篇名为"[读书笔记]长尾理论"的文章. 我

【Python3 爬虫】爬取博客园首页所有文章

首先,我们确定博客园首页地址为:https://www.cnblogs.com/ 我们打开可以看到有各种各样的文章在首页,如下图: 我们以上图标记的文章为例子吧!打开网页源码,搜索Docker,搜索结果如下图: 从上图后红色标记部分可以看出,我们使用正则表达式即可匹配该网址,我们匹配到该网址之后,将该网址对应的内容下载到到底进行存储. 实现代码 import urllib.request import re """ 爬取cnblogs首页所有的文章 ""&

python——关于简单爬取博客园班级成员发的博文的题目、发布人、阅读、评论,再存到csv文件中

因为老师要以班里每个人发的博客质量作为最后总成绩的评定的一部分,就要把班上所有同学发的博客都统计起来,可以用来评定的因素有:阅读.评论.推荐等,但因为今天只是做一个简单的爬取,推荐这个元素在班级博客中需要点开每一篇博文才能看到获取,就不爬取了,只爬取阅读和推荐,加上每篇博文的发布人和标题. 我先会放上代码,再逐条解释其含义及作用. 代码如下(其中爬取的网页是以我自己的班级为例): 1 from bs4 import BeautifulSoup 2 import pandas as pd 3 im