新建项目

# 新建项目
$ scrapy startproject jianshu
# 进入到文件夹
$ cd jainshu
# 新建spider文件
$ scrapy genspider -t crawl jianshu_spider jainshu.com

items.py文件

import scrapy

class ArticleItem(scrapy.Item):
title = scrapy.Field()
content = scrapy.Field()
article_id = scrapy.Field()
origin_url = scrapy.Field()
author = scrapy.Field()
avatar = scrapy.Field()
pub_time = scrapy.Field()

jianshu_spider.py文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jianshu.items import ArticleItem class JianshuSpiderSpider(CrawlSpider):
name = 'jianshu_spider'
allowed_domains = ['jianshu.com']
start_urls = ['https://www.jianshu.com/'] rules = (
Rule(LinkExtractor(allow=r'.*/p/[0-9a-z]{12}.*'), callback='parse_detail', follow=True),
) def parse_detail(self, response):
title = response.xpath("//h1[@class='title']/text()").get()
content = response.xpath("//div[@class='show-content-free']").get()
avatar = response.xpath("//a[@class='avatar']/img/@src").get()
author = response.xpath("//div[@class='info']/span/a/text()").get()
pub_time = response.xpath("//span[@class='publish-time']/text()").get()
article_id = response.url.split("?")[0].split("/")[-1]
origin_url = response.url
item = ArticleItem(
title=title,
content=content,
avatar=avatar,
pub_time=pub_time,
article_id=article_id,
origin_url=origin_url,
author=author
)
yield item

同步的MySQL插入数据

import pymysql

class JianshuPipeline(object):
def __init__(self):
dbparams = {
'host': '127.0.0.1',
'user': 'root',
'password': '',
'database': 'jianshu',
'port': 3306,
'charset': 'utf8'
}
self.conn = pymysql.connect(**dbparams)
self.cursor = self.conn.cursor()
self._sql = None def process_item(self, item, spider):
self.cursor.execute(self.sql, (item['title'], item['content'], item['author'], item['avatar'], \
item['pub_time'], item['origin_url'], item['article_id']))
self.conn.commit()
return item @property
def sql(self):
if not self._sql:
self._sql = """
insert into article(title,content, author, avatar, pub_time, origin_url, article_id) values (%s, %s, %s, %s, %s, %s,%s)
"""
return self._sql
return self._sql

异步的MySQL插入数据

from twisted.enterprise import adbapi
from pymysql import cursors
class JianshuTwistedPipeline(object):
def __init__(self):
dbparams = {
'host': '127.0.0.1',
'user': 'root',
'password': '',
'database': 'jianshu',
'port': 3306,
'charset': 'utf8',
'cursorclass': cursors.DictCursor
}
self.dbpool = adbapi.ConnectionPool('pymysql', **dbparams)
self._sql = None @property
def sql(self):
if not self._sql:
self._sql = """
insert into article(title,content, author, avatar, pub_time, origin_url, article_id) values (%s, %s, %s, %s, %s, %s,%s)
"""
return self._sql
return self._sql def process_item(self, item, spider):
defer = self.dbpool.runInteraction(self.insert_item, item)
defer.addErrback(self.handle_error, item, spider) def insert_item(self, cursor, item):
cursor.execute(self.sql, (item['title'], item['content'], item['author'], item['avatar'], \
item['pub_time'], item['origin_url'], item['article_id'])) def handle_error(self, error, item, spider):
print('=' * 10 + 'error' + '=' * 10)
print(error)
print('=' * 10 + 'error' + '=' * 10)

爬虫第六篇:scrapy框架爬取某书网整站爬虫爬取的更多相关文章

  1. python爬虫实战:利用scrapy,短短50行代码下载整站短视频

    近日,有朋友向我求助一件小事儿,他在一个短视频app上看到一个好玩儿的段子,想下载下来,可死活找不到下载的方法.这忙我得帮,少不得就抓包分析了一下这个app,找到了视频的下载链接,帮他解决了这个小问题 ...

  2. 爬虫(十六):Scrapy框架(三) Spider Middleware、Item Pipeline

    1. Spider Middleware Spider Middleware是介入到Scrapy的Spider处理机制的钩子框架. 当Downloader生成Response之后,Response会被 ...

  3. 爬虫(十四):Scrapy框架(一) 初识Scrapy、第一个案例

    1. Scrapy框架 Scrapy功能非常强大,爬取效率高,相关扩展组件多,可配置和可扩展程度非常高,它几乎可以应对所有反爬网站,是目前Python中使用最广泛的爬虫框架. 1.1 Scrapy介绍 ...

  4. Python爬虫进阶三之Scrapy框架安装配置

    初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了,不过还有更加强大的工具,爬虫框架Scrapy,这安装过程也是煞费苦心哪,在此整理如下. Windows 平台: 我的系统是 ...

  5. quotes 整站数据爬取存mongo

    安装完成scrapy后爬取部分信息已经不能满足躁动的心了,那么试试http://quotes.toscrape.com/整站数据爬取 第一部分 项目创建 1.进入到存储项目的文件夹,执行指令 scra ...

  6. python网络爬虫(2)——scrapy框架的基础使用

    这里写一下爬虫大概的步骤,主要是自己巩固一下知识,顺便复习一下. 一,网络爬虫的步骤 1,创建一个工程 scrapy startproject 工程名称 创建好工程后,目录结构大概如下: 其中: sc ...

  7. 爬虫(九)scrapy框架简介和基础应用

    概要 scrapy框架介绍 环境安装 基础使用 一.什么是Scrapy? Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,非常出名,非常强悍.所谓的框架就是一个已经被集成了各种功能 ...

  8. Python3爬虫(十七) Scrapy框架(一)

    Infi-chu: http://www.cnblogs.com/Infi-chu/ 1.框架架构图: 2.各文件功能scrapy.cfg 项目的配置文件items.py 定义了Item数据结构,所有 ...

  9. 爬虫 (5)- Scrapy 框架简介与入门

    Scrapy 框架 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页 ...

随机推荐

  1. Visual Assist X助手的一些使用技巧和快捷键

    部分快捷键 Shift+Alt+F // Find References 查找引用 Shift+Alt+S // FindSynbolDialog打开查找符号对话框 Alt+G // GotoImpl ...

  2. finereport-JS

    JS实现定时刷新报表 setInterval("self.location.reload();",10000); //10000ms即每10s刷新一次页面. 注:对于cpt报表,若 ...

  3. What is Grammar?

    What is Grammar? And why grammar is your friend… Grammar(noun): the structure and system of a langua ...

  4. iPhone设备分辨率一览

    地址:https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/launch-screen/

  5. python中open函数的使用

    转自:https://www.cnblogs.com/R-ling/p/8412578.html 一.open()的函数原型open(file, mode=‘r', buffering=-1, enc ...

  6. 关于jQuery中nth-child和nth-of-type的详解

    首先贴出来HTML的代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  7. java maven项目打包

    使用IDEA打包,首先调出来maven projects窗口: 菜单栏Help->Find Action(Ctrl+Shift+A),输入Maven projects https://blog. ...

  8. Hidden String---hdu5311(字符串处理)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5311 题意:从给出的串 s 中找到3个子串然后把他们连在一起问是否能够成anniversary #in ...

  9. django博客项目9

    ................

  10. DRF(2) - 解析器,序列化组件使用(GET/POST接口设计)

    一.DRF - 解析器 1.解析器的引出 我们知道,浏览器可以向django服务器发送json格式的数据,此时,django不会帮我们进行解析,只是将发送的原数据保存在request.body中,只有 ...