scrapy爬取简书整站文章
在这里我们使用CrawlSpider爬虫模板, 通过其过滤规则进行抓取, 并将抓取后的结果存入mysql中,下面直接上代码:
jianshu_spider.py
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jianshu.items import JianshuItem
import html class JianshuSpiderSpider(CrawlSpider):
name = 'jianshu_spider'
allowed_domains = ['jianshu.com']
start_urls = ['http://jianshu.com/'] rules = (
Rule(LinkExtractor(allow=r'.*/p/[0-9a-z]{12}.*'), callback='parse_article', follow=True),
) def parse_article(self, response):
article_code = response.url.split("?")[0].split("/")[-1]
title = response.xpath('//h1[@class="title"]/text()').get().strip()
author = response.xpath('//div[contains(@class, "author")]/div[@class="info"]//span[@class="name"]/a/text()').get().strip()
head_img = response.xpath('//div[contains(@class, "author")]/a[@class="avatar"]/img/@src').get()
pub_time = response.xpath('//span[@class="publish-time"]/text()').get().strip().replace('*','')
head_img_url = "http:{}".format(head_img)
# 存储到数据库中,需要对‘/’转义
# content = html.escape(response.xpath('//div[@class="show-content"]').get())
content = response.xpath('//div[@class="show-content"]').get() yield JianshuItem(
article_code = article_code,
title = title,
author = author,
head_img_url = head_img_url,
content = content,
pub_time = pub_time,)
items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html import scrapy class JianshuItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
article_code = scrapy.Field()
title = scrapy.Field()
author = scrapy.Field()
pub_time = scrapy.Field()
head_img_url = scrapy.Field()
content = scrapy.Field()
pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from jianshu import model class JianshuPipeline(object): def __init__(self):
self.session = model.DBSession() def process_item(self, item, spider):
# 这里的item属于字典类型
article = model.Article(**item)
try:
self.session.add(article)
self.session.commit()
except Exception as e:
print("="*100)
print("INSERT ERROR!")
self.session.rollback()
return item
def open_spider(self, spider):
pass def close_spider(self, spider):
self.session.close()
model.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import String, Text, Time, Column, Integer, VARCHAR
from sqlalchemy.orm import sessionmaker # 创建数据库链接接口
engine = create_engine("mysql+pymysql://jianshu:jianshu@localhost:3306/jianshu?charset=utf8mb4", echo=False) # 声明映像, 即实际数据库表的基本准则的映射类
# 其维持类和数据库表关系目录
Base = declarative_base() class Article(Base): __tablename__ = "jianshu_article" id = Column(Integer, autoincrement=True, primary_key=True)
article_code = Column(String(16), nullable=False)
title = Column(Text)
author = Column(String(16))
pub_time = Column(Time)
head_img_url = Column(VARCHAR(256))
content = Column(Text) DBSession = sessionmaker(bind=engine) if __name__ == '__main__':
Base.metadata.create_all(engine)
scrapy爬取简书整站文章的更多相关文章
- python2.7 爬取简书30日热门专题文章之简单分析_20170207
昨天在简书上写了用Scrapy抓取简书30日热门文章,对scrapy是刚接触,跨页面抓取以及在pipelines里调用settings,连接mysql等还不是很熟悉,今天依旧以单独的py文件区去抓取数 ...
- Scrapy+selenium爬取简书全站
Scrapy+selenium爬取简书全站 环境 Ubuntu 18.04 Python 3.8 Scrapy 2.1 爬取内容 文字标题 作者 作者头像 发布日期 内容 文章连接 文章ID 思路 分 ...
- Node爬取简书首页文章
Node爬取简书首页文章 博主刚学node,打算写个爬虫练练手,这次的爬虫目标是简书的首页文章 流程分析 使用superagent发送http请求到服务端,获取HTML文本 用cheerio解析获得的 ...
- python3 爬取简书30日热门,同时存储到txt与mongodb中
初学python,记录学习过程. 新上榜,七日热门等同理. 此次主要为了学习python中对mongodb的操作,顺便巩固requests与BeautifulSoup. 点击,得到URL https: ...
- Python爬取简书主页信息
主要学习如何通过抓包工具分析简书的Ajax加载,有时间再写一个Multithread proxy spider提升效率. 1. 关键点: 使用单线程爬取,未登录,爬取简书主页Ajax加载的内容.主要有 ...
- Scrapy爬取伯乐在线的所有文章
本篇文章将从搭建虚拟环境开始,爬取伯乐在线上的所有文章的数据. 搭建虚拟环境之前需要配置环境变量,该环境变量的变量值为虚拟环境的存放目录 1. 配置环境变量 2.创建虚拟环境 用mkvirtualen ...
- 【python3】爬取简书评论生成词云
一.起因: 昨天在简书上看到这么一篇文章<中国的父母,大都有毛病>,看完之后个人是比较认同作者的观点. 不过,翻了下评论,发现评论区争议颇大,基本两极化.好奇,想看看整体的评论是个什么样, ...
- 爬取简书图片(使用BeautifulSoup)
import requests from bs4 import BeautifulSoup url_list = [] kv = {'User-Agent':'Mozilla/5.0'} r = re ...
- python 爬取简书评论
import json import requests from lxml import etree from time import sleep url = "https://www.ji ...
随机推荐
- 离散化+线段树/二分查找/尺取法 HDOJ 4325 Flowers
题目传送门 题意:给出一些花开花落的时间,问某个时间花开的有几朵 分析:这题有好几种做法,正解应该是离散化坐标后用线段树成端更新和单点询问.还有排序后二分查找询问点之前总花开数和总花凋谢数,作差是当前 ...
- 题解报告:hdu 1166 敌兵布阵(线段树or树状数组)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166 Problem Description C国的死对头A国这段时间正在进行军事演习,所以C国间谍头 ...
- 彩色模型 分类: 图像处理 Matlab 2015-01-08 20:43 364人阅读 评论(0) 收藏
彩色模型(又称彩色空间或彩色系统)是描述色彩的一种方法,本质上,彩色模型就是坐标系统和子空间的规范,系统中的每种颜色由单个点来表示.下面介绍两种最常用的彩色模型. 一.RGB彩色模型: RGB模型是最 ...
- ORACLE数据库的备份分为物理备份和逻辑备份两种。
物理备份是将实际组成数据库的操作系统文件从一处拷贝到另一处的备份过程,通常是从磁盘到磁带.可以使用 Oracle 的恢复管理器(Recovery Manager,RMAN)或操作系统命令进行数据库的物 ...
- TC 609DIV2(950)
Problem Statement Vocaloids Gumi, Ia, and Mayu love singing. They decided to make an album comp ...
- node入门(二)——gulpfile.js初探
本文关于gulpfile.js怎么写,利于完成个性化需求.本文开发环境默认已安装node,详情参考<node入门(一)——安装>. 一.安装gulp npm install -g gulp ...
- SQL常用自定义函数
1.字符串转Table(Func_SplitToTable) CREATE FUNCTION [dbo].[Func_SplitToTable] ( @SplitString ...
- poj2991 Crane
思路: 线段树每个节点维护第一条线段起点指向最后一条线段终点的向量,于是每一个操作都是一次区间更新.使用成段更新的线段树即可.实现: #include <cstdio> #include ...
- struts2的action是线程安全的,struts1的action不是线程安全的真正原因
为什么struts2的action是线程安全的,struts1的action不是线程安全的? 先对struts1和struts2的原理做一个简单的讲解 对于struts1 ,当第一次**.do的请求过 ...
- pthread Win32多线程编程的一些知识和感想
研究遗传算法的一大诟病就是每次运行程序的结果并不是完全一样的,有时候能找到最优解有时候找不到最优解,这就是遗传算法的概率性导致的.那么怎么评价你的方法的好坏呐,这时候就要多次独立运行程序最后取结果的平 ...