1:创建项目

2:创建爬虫

3:编写start.py文件用于运行爬虫程序

# -*- coding:utf-8 -*-
#作者:    baikai
#创建时间: 2018/12/14 14:09
#文件:    start.py
#IDE:    PyCharm
from scrapy import cmdline

cmdline.execute("scrapy crawl js".split())

4:设置settings.py文件的相关设置

爬取详情页数据

编写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 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()

编写js.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jianshu_spider.items import ArticleItem

class JsSpider(CrawlSpider):
    name = 'js'
    allowed_domains = ['jianshu.com']
    start_urls = ['https://www.jianshu.com/']

    rules = (
        # 匹配地址https://www.jianshu.com/p/d8804d18d638
        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()
        #作者图像
        avatar=response.xpath("//a[@class='avatar']/img/@src").get()
        author=response.xpath("//span[@class='name']/a/text()").get()
        #发布时间
        pub_time=response.xpath("//span[@class='publish-time']/text()").get()
        #详情页id
        url=response.url
        #https://www.jianshu.com/p/d8804d18d638
        url1=url.split("?")[0]
        article_id=url1.split("/")[-1]
        #文章内容
        content=response.xpath("//div[@class='show-content']").get()

        item=ArticleItem(
            title=title,
            avatar=avatar,
            author=author,
            pub_time=pub_time,
            origin_url=response.url,
            article_id=article_id,
            content=content
        )
        yield item

设计数据库和表

数据库jianshu

表article

id设置为自动增长

将爬取到的数据存储到mysql数据库中

# -*- 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

import pymysql
from twisted.enterprise import adbapi
from pymysql import cursors

class JianshuSpiderPipeline(object):
    def __init__(self):
        dbparams = {
            'host': '127.0.0.1',
            'port': 3306,
            'user': 'root',
            'password': '8Wxx.ypa',
            'database': 'jianshu',
            '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(id,title,content,author,avatar,pub_time,origin_url,article_id) values(null,%s,%s,%s,%s,%s,%s,%s)
                """
            return self._sql
        return self._sql

运行start.py效果如下

python scrapy 实战简书网站保存数据到mysql的更多相关文章

  1. SpringMVC保存数据到mysql乱码问题

    SpringMVC保存数据到mysql乱码问题 乱码问题常见配置 一.web.xml配置过滤器 <filter> <filter-name>encoding-filter< ...

  2. hibernate保存数据到mysql时的中文乱码问题

    因为hibernate底层使用的是jdbc的技术,所以我参考了别人使用jdbc保存数据到mysql里面时解决乱码问题的方法! 首先要告诉数据库要插入的字符串的字符集,mysql 默认使用的字符集是 l ...

  3. python scrapy实战糗事百科保存到json文件里

    编写qsbk_spider.py爬虫文件 # -*- coding: utf-8 -*- import scrapy from qsbk.items import QsbkItem from scra ...

  4. Python爬取简书主页信息

    主要学习如何通过抓包工具分析简书的Ajax加载,有时间再写一个Multithread proxy spider提升效率. 1. 关键点: 使用单线程爬取,未登录,爬取简书主页Ajax加载的内容.主要有 ...

  5. Python Scrapy 实战

    Python Scrapy 什么是爬虫? 网络爬虫(英语:web crawler),也叫网络蜘蛛(spider),是一种用来自动浏览万维网的网络机器人.其目的一般为编纂网络索引. Python 爬虫 ...

  6. 教程+资源,python scrapy实战爬取知乎最性感妹子的爆照合集(12G)!

    一.出发点: 之前在知乎看到一位大牛(二胖)写的一篇文章:python爬取知乎最受欢迎的妹子(大概题目是这个,具体记不清了),但是这位二胖哥没有给出源码,而我也没用过python,正好顺便学一学,所以 ...

  7. Scrapy Item用法示例(保存item到MySQL数据库,MongoDB数据库,使用官方组件下载图片)

    需要学习的地方: 保存item到MySQL数据库,MongoDB数据库,下载图片 1.爬虫文件images.py # -*- coding: utf-8 -*- from scrapy import ...

  8. Spark使用Java读取mysql数据和保存数据到mysql

    原文引自:http://blog.csdn.net/fengzhimohan/article/details/78471952 项目应用需要利用Spark读取mysql数据进行数据分析,然后将分析结果 ...

  9. 利用python scrapy 框架抓取豆瓣小组数据

    因为最近在找房子在豆瓣小组-上海租房上找,发现搜索困难,于是想利用爬虫将数据抓取. 顺便熟悉一下Python. 这边有scrapy 入门教程出处:http://www.cnblogs.com/txw1 ...

随机推荐

  1. 编译Win32动态库工程的两个链接错误的解决

    作者:朱金灿 来源:http://blog.csdn.net/clever101 今天编译一个Win32动态库工程,出现两个链接错误的解决,一个是: main.obj: error LNK2001: ...

  2. 被遗忘的设计模式——空对象模式(Null Object Pattern)

    GoF(四人帮)那本<设计模式 可复用面向对象软件的基础>可谓是设计模式方面的经典之作,其中介绍的23种设计模式, 也可谓是经典中的经典.但是,设计模式的种类绝不仅仅是这23种,除此之外还 ...

  3. 1.jdk的安装

    1.下载jdk放到某(E)盘底下的(java)某文件夹里 2.配置环境变量 (1)配置JAVA_HOME,CLASSPATH,PATH三个变量 其中JAVA_HOME必须的 JAVA_HOME=E:\ ...

  4. simotion byte/word ASCII码转换为字符、字符串

    建立string类型,和byte类型(ASCII)的数据 将byte类型(ASCII)赋值给string中的一个字符 参考程序 VAR_GLOBAL myword :WORD; mystring :S ...

  5. sublim的正则匹配(待续)

    ctrl+H 打开匹配模式 打开正则匹配模式 正则匹配的一些方法:  点代表的是任意字符.* 代表的是取 0 至 无限长度问号代表的是非贪婪模式.三个链接在一起是取尽量少的任意字符,一般不会这么单独写 ...

  6. SAP UI5和CRM WebUI的View和Controller是如何绑定的

    UI5 例如我在UI5的界面上画一个按钮,点击之后弹出一个Alert dialog. 在XML view里只定义了controller的名称和事件处理函数的名称.那么按钮被点击之后,controlle ...

  7. Selenium入门10 弹出框的处理 switch_to.alert

      三种弹出框alert(一个按钮),confirm(两个确认,取消),prompt(两个按钮+输入框). 切换到弹框: switch_to_alert()  新版的selenium用:  brows ...

  8. python学习接口测试(二)

    .python接口之http请求 python的强大之处在于提供了很多的标准库以及第三库,本文介绍urllib 和第三库的requests. Urllib 定义了很多函数和类,这些函数和类能够帮助我们 ...

  9. 使用筛法在 O(logN) 的时间内查询多组数的素数因子

    Prime Factorization using Sieve O(log n) for multiple queries 使用筛法在 O(logN) 的时间内查询多组数的素数因子 前言 通常, 我们 ...

  10. django验证码功能

    1.目的 现在我们一般访问网页都需要输入验证码,比如博客园,有的甚至是通过手机验证码实时登录.这样做的目的主要还是为了防止其他人的恶意访问,比如爬虫,下面就来看看验证码是如何实现的 2.StringI ...