The python crawling scrapy save data database to mysql

1. Create Project

scrapy startproject tencent

2. Create a project

scrapy genspider mahuateng

3, since saved to the database, naturally you want to install pymsql

pip install pymysql

4, settings files, configuration information, including databases, etc.

# -*- 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
#= True HTTPCACHE_ENABLED 
# HTTPCACHE_EXPIRATION_SECS = 0 
# HTTPCACHE_DIR = 'HttpCache' 
# HTTPCACHE_IGNORE_HTTP_CODES = [] 
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' 



# connection data the MySQL 
# database address 
MYSQL_HOST = ' localhost ' 
# database Username: 
mysql_user = ' root ' 
# database password 
MYSQL_PASSWORD = ' yang156122 ' 
# database port 
MYSQL_PORT = 3306 # database name 
MYSQL_DBNAME = ' the Test '

# Database encoding 
MYSQL_CHARSET = ' UTF8 '
View Code

5, items.py file defines the data fields

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

6, mahuateng.py document was crawling data

# -*- 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
            )
View Code

7, pipelines.py document was to process data, including storing data in 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
#Import MYSQL_DBNAME tencent.settings from 
# 
# from tencent.settings Import MYSQL_CHARSET 
Import Copy
 class TencentPipeline (Object):
     # function initializes 
    DEF  the __init__ (Self, db_pool): 
        self.db_pool = db_pool 

    @classmethod 
    DEF from_settings (CLS, Settings):
         "" " class method, loaded only once, database initialization " "" 
        db_params = dict ( 
            Host = Settings [ ' MYSQL_HOST ' ], 
            User = Settings [ ' mysql_user '], 
            Password = Settings [ ' MYSQL_PASSWORD ' ], 
            Port = Settings [ ' the MYSQL_PORT ' ], 
            Database = Settings [ ' MYSQL_DBNAME ' ], 
            charset = Settings [ ' MYSQL_CHARSET ' ], 
            use_unicode = True,
             # the cursor type 
            cursorClass = Cursors. DictCursor 
        ) 
        # Create a connection pool 
        db_pool the adbapi.ConnectionPool = ( ' pymysql ', ** db_params)
         # Returns a pipeline objects 
        return CLS (db_pool) 

    DEF process_item (Self, Item, Spider):
         "" " 
        Data processing 
        : param Item: 
        : param Spider: 
        : return: 
        " "" 
        myItem = {} 
        myItem [ " postId " ] Item = [ " the 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)
        #Copy of the object, a deep copy --- here is to solve the problem of duplication of data! ! ! 
        = asynItem copy.deepcopy (myItem) 

        # to be executed into sql connection pool 
        Query = self.db_pool.runInteraction (self.insert_into, asynItem) 

        # If sql performs transmission error, automatic callback addErrback () function 
        query.addErrback (self .handle_error, myItem, Spider)
         return myItem 


    # handling sql function 
    DEF insert_into (Self, the Cursor, Item):
         # create sql statement 
        sql = " INSERT INTO tencent (postId, recruitPostId, recruitPostName, countryName, locationName, categoryName, LastUpdateTime) VALUES ( '{}', '{}', '{}', '{}', '{}', '{}', '{}') " .postId ' ], Item [ ' recruitPostId ' ], Item [ ' recruitPostName ' ], Item [ ' countryName ' ], Item [ ' locationName ' ], 
            Item [ ' categoryName ' ], Item [ ' LastUpdateTime ' ])
         # execute sql statement 
        cursor.execute (SQL)
         # error function 

    DEF the handle_error (Self, failure, Item, Spider):
         # # output an error message 
        Print ( " failure ", failure)
View Code

8, create a database table

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;

Perfect ending!

Guess you like

Origin www.cnblogs.com/ywjfx/p/11102081.html