python之scrapy爬取数据保存到mysql数据库

1、创建工程

scrapy startproject tencent

2、创建项目

scrapy genspider mahuateng

3、既然保存到数据库,自然要安装pymsql

pip install pymysql

4、settings文件,配置信息,包括数据库等

# -*- coding: utf-8 -*-

# Scrapy settings for tencent project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = ‘tencent‘

SPIDER_MODULES = [‘tencent.spiders‘]
NEWSPIDER_MODULE = ‘tencent.spiders‘

LOG_LEVEL="WARNING"
LOG_FILE="./qq.log"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36‘

# Obey robots.txt rules
#ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   ‘Accept‘: ‘text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8‘,
#   ‘Accept-Language‘: ‘en‘,
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    ‘tencent.middlewares.TencentSpiderMiddleware‘: 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    ‘tencent.middlewares.TencentDownloaderMiddleware‘: 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    ‘scrapy.extensions.telnet.TelnetConsole‘: None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   ‘tencent.pipelines.TencentPipeline‘: 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = ‘httpcache‘
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = ‘scrapy.extensions.httpcache.FilesystemCacheStorage‘

# 连接数据MySQL
# 数据库地址
MYSQL_HOST = ‘localhost‘
# 数据库用户名:
MYSQL_USER = ‘root‘
# 数据库密码
MYSQL_PASSWORD = ‘yang156122‘
# 数据库端口
MYSQL_PORT = 3306
# 数据库名称
MYSQL_DBNAME = ‘test‘
# 数据库编码
MYSQL_CHARSET = ‘utf8‘

5、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 TencentItem(scrapy.Item):
    """
    数据字段定义
    """
    postId = scrapy.Field()
    recruitPostId = scrapy.Field()
    recruitPostName = scrapy.Field()
    countryName = scrapy.Field()
    locationName = scrapy.Field()
    categoryName = scrapy.Field()
    lastUpdateTime = scrapy.Field()

    pass

6、mahuateng.py文件主要是抓取数据

# -*- coding: utf-8 -*-
import scrapy

import json
import logging
class MahuatengSpider(scrapy.Spider):
    name = ‘mahuateng‘
    allowed_domains = [‘careers.tencent.com‘]
    start_urls = [‘https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1561688387174&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=40003&attrId=&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn‘]
    pageNum = 1
    def parse(self, response):
        """
        数据获取
        :param response:
        :return:
        """
        content = response.body.decode()
        content = json.loads(content)
        content=content[‘Data‘][‘Posts‘]
        #删除空字典
        for con in content:
            #print(con)
            for key in list(con.keys()):
                if not con.get(key):
                    del con[key]
        #记录每一个岗位信息
        # for con in content:
        #     yield con
            #print(type(con))
            yield con
            #logging.warning(con)

        #####翻页######
        self.pageNum = self.pageNum+1
        if self.pageNum<=118:
            next_url = "https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1561688387174&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=40003&attrId=&keyword=&pageIndex="+str(self.pageNum)+"&pageSize=10&language=zh-cn&area=cn"
            yield  scrapy.Request(
                next_url,
                callback=self.parse
            )

7、pipelines.py文件主要是对数据进行处理,包括将数据存储到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 logging

from pymysql import cursors
from twisted.enterprise import adbapi
import time
# from tencent.settings import MYSQL_HOST
# from tencent.settings import MYSQL_USER
# from tencent.settings import MYSQL_PASSWORD
# from tencent.settings import MYSQL_PORT
# from tencent.settings import MYSQL_DBNAME
#
# from tencent.settings import MYSQL_CHARSET
import copy
class TencentPipeline(object):
    #函数初始化
    def __init__(self,db_pool):
        self.db_pool=db_pool

    @classmethod
    def from_settings(cls,settings):
        """类方法,只加载一次,数据库初始化"""
        db_params = dict(
            host=settings[‘MYSQL_HOST‘],
            user=settings[‘MYSQL_USER‘],
            password=settings[‘MYSQL_PASSWORD‘],
            port=settings[‘MYSQL_PORT‘],
            database=settings[‘MYSQL_DBNAME‘],
            charset=settings[‘MYSQL_CHARSET‘],
            use_unicode=True,
            # 设置游标类型
            cursorclass=cursors.DictCursor
        )
        # 创建连接池
        db_pool = adbapi.ConnectionPool(‘pymysql‘, **db_params)
        # 返回一个pipeline对象
        return cls(db_pool)

    def process_item(self, item, spider):
        """
        数据处理
        :param item:
        :param spider:
        :return:
        """
        myItem={}
        myItem["postId"] = item["PostId"]
        myItem["recruitPostId"] = item["RecruitPostId"]
        myItem["recruitPostName"] = item["RecruitPostName"]
        myItem["countryName"] = item["CountryName"]
        myItem["locationName"] = item["LocationName"]
        myItem["categoryName"] = item["CategoryName"]
        myItem["lastUpdateTime"] = item["LastUpdateTime"]
        logging.warning(myItem)
        # 对象拷贝,深拷贝  --- 这里是解决数据重复问题!!!
        asynItem = copy.deepcopy(myItem)

        # 把要执行的sql放入连接池
        query = self.db_pool.runInteraction(self.insert_into, asynItem)

        # 如果sql执行发送错误,自动回调addErrBack()函数
        query.addErrback(self.handle_error, myItem, spider)
        return myItem

    # 处理sql函数
    def insert_into(self, cursor, item):
        # 创建sql语句
        sql = "INSERT INTO tencent (postId,recruitPostId,recruitPostName,countryName,locationName,categoryName,lastUpdateTime) VALUES (‘{}‘,‘{}‘,‘{}‘,‘{}‘,‘{}‘,‘{}‘,‘{}‘)".format(
            item[‘postId‘], item[‘recruitPostId‘], item[‘recruitPostName‘], item[‘countryName‘], item[‘locationName‘],
            item[‘categoryName‘],item[‘lastUpdateTime‘])
        # 执行sql语句
        cursor.execute(sql)
        # 错误函数

    def handle_error(self, failure, item, spider):
        # #输出错误信息
        print("failure", failure)

8、创建数据库表

Navicat MySQL Data Transfer

Source Server         : 本机
Source Server Version : 50519
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50519
File Encoding         : 65001

Date: 2019-06-28 12:47:06
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tencent
-- ----------------------------
DROP TABLE IF EXISTS `tencent`;
CREATE TABLE `tencent` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postId` varchar(100) DEFAULT NULL,
  `recruitPostId` varchar(100) DEFAULT NULL,
  `recruitPostName` varchar(100) DEFAULT NULL,
  `countryName` varchar(100) DEFAULT NULL,
  `locationName` varchar(100) DEFAULT NULL,
  `categoryName` varchar(100) DEFAULT NULL,
  `lastUpdateTime` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1181 DEFAULT CHARSET=utf8;

完美收官!

原文地址:https://www.cnblogs.com/ywjfx/p/11102081.html

时间: 2024-10-29 19:09:49

python之scrapy爬取数据保存到mysql数据库的相关文章

Python scrapy爬虫数据保存到MySQL数据库

除将爬取到的信息写入文件中之外,程序也可通过修改 Pipeline 文件将数据保存到数据库中.为了使用数据库来保存爬取到的信息,在 MySQL 的 python 数据库中执行如下 SQL 语句来创建 job_inf 数据表: CREATE TABLE job inf ( id INT (11) NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR (255), salary VARCHAR (255), company VARCHAR (255),

关于爬取数据保存到json文件,中文是unicode解决方式

流程: 爬取的数据处理为列表,包含字典.里面包含中文, 经过json.dumps,保存到json文件中, 发现里面的中文显示未\ue768这样子 查阅资料发现,json.dumps 有一个参数.ensure_ascii =true,  它会将不是ascii字符的转义为json 字符串. 如果是false ,不是ascii字符的会包含在里面,即如果是中文就会保存中文. 但是我认为json这样写是有道理的. 用requests模块, requests.post(url,json=handled_da

php将图片以二进制保存到mysql数据库并显示

一.存储图片的数据表结构: -- -- 表的结构 `image` -- CREATE TABLE IF NOT EXISTS `image` ( `id` int(3) NOT NULL AUTO_INCREMENT, `name` varchar(100) CHARACTER SET utf8 NOT NULL, `pic` blob NOT NULL, `type` varchar(50) CHARACTER SET utf8 NOT NULL, `date` datetime NOT NU

php将图片保存到mysql数据库及从数据库中读取图片的方法源码 转

php将图片保存到mysql数据库及从数据库中读取图片的方法源码 分类: 网站 2012-03-11 15:25 5059人阅读 评论(0) 收藏 举报 数据库mysqlphpsql serverquerydatabase 一般来讲都是把图片保存到服务器下,然后根据路径读出的,但是有时候出于安全及版权什么的考虑,会把图片保存到mysql的数据库中,然后再读出来,这样的图片点击右键属性,是看不到图片地址的.下面逍遥一生就介绍下如何用php把图片存储到mysql中及如何读出.     MySQL数据

python爬取数据并保存到数据库中(第一次练手完整代码)

1.首先,下载需要的模块requests, BeautifulSoup, datetime, pymysql(注意,因为我用的python3.7,不支持mysqldb了),具体的下载方法有pip下载,或者使用Anaconda版本python的童鞋可以使用conda下载. 2.创建conndb,py,包含数据库的连接断开,增删改查等操作: #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql def conn_db(): # 连接数

Python爬虫:爬取小说并存储到数据库

爬取小说网站的小说,并保存到数据库 第一步:先获取小说内容 #!/usr/bin/python # -*- coding: UTF-8 -*- import urllib2,re domain = 'http://www.quanshu.net' headers = {     "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom

利用session_set_save_handler()函数将session保存到MySQL数据库中

PHP保存session默认的是采用的文件的方式来保存的,这仅仅在文件的空间开销很小的windows上是可以采用的,但是如果我们采用uinx或者是liux上的文件系统的时候,这样的文件系统的文件空间开销是很大的,然而session是要时时刻刻的使用的,大量的用户就要创建很多的session文件,这样对整个的服务器带来性能问题. 另一方面,如果服务器起采用群集的方式的话就不能保持session的一致性,所以我们就绪要采用数据库的方式来保存session,这样,不管有几台服务器同时使用,只要把他们的

python爬虫抓取51cto博客大牛的文章保存到MySQL数据库

脚本实现:获取51cto网站某大牛文章的url,并存储到数据库中. #!/usr/bin/env python #coding:utf-8 from  bs4  import  BeautifulSoup import urllib import re import MySQLdb k_art_name = [] v_art_url = [] db = MySQLdb.connect('192.168.115.5','blog','blog','blog') cursor = db.cursor

将 node.js 的数据保存到 mongo 数据库中

Mongo 数据库 安装 首先到 Mongo 的官方网站下载安装程序:http://www.mongodb.org/,我下载的文件名为:mongodb-win32-x86_64-2008plus-2.6.4-signed.msi 执行安装程序. 下一步 同意许可协议 可以选择定制 Custom 看一下. 全部装上吧. 开始实际安装. MongoDB 默认安装到了 C:\Program Files\MongoDB 2.6 Standard\bin 目录下,但是,没有自动添加到 Path 路径中,手