(75)--用框架爬取腾讯招聘信息并保存到数据库

# 用框架爬取腾讯招聘信息并保存到数据库

# main.py

from scrapy import cmdline

cmdline.execute('scrapy crawl tencent_new'.split())


# tencent_new.py

# -*- coding: utf-8 -*-
import scrapy
from urllib import request,parse
from ..items import JobItem
from datetime import datetime

class TencentNewSpider(scrapy.Spider):
    name = 'tencent_new'
    allowed_domains = ['tencent.com']
    start_urls = ['http://hr.tencent.com']

    base_url = 'https://hr.tencent.com/position.php?start=%d'

    def parse(self, response):
        # 构造分页请求
        for i in range(0,100 + 1,10):
            fullurl = self.base_url % i
            yield scrapy.Request(fullurl,callback=self.parse_list)

    # 解析列表页
    def parse_list(self,response):
        # print(response.url)
        detail_list = response.xpath('//td[@class="l square"]/a/@href').extract()
        for link in detail_list:
            link = request.urljoin(self.base_url,link)

            yield scrapy.Request(link,callback=self.parse_detail)

    # 解析详情页
    def parse_detail(self,response):
        item = JobItem()

        p_name = response.xpath('//td[@id="sharetitle"]/text()').extract_first()
        p_location = response.xpath('//tr[@class="c bottomline"]/td[1]/text()').extract_first()
        p_type = response.xpath('//tr[@class="c bottomline"]/td[2]/text()').extract_first()
        p_number = response.xpath('//tr[@class="c bottomline"]/td[3]/text()').extract_first()

        # print(p_name,p_location,p_type,p_number)

        p_info = response.xpath('//ul[@class="squareli"]')
        p_duty = p_info[0]
        p_require = p_info[1]

        p_duty = p_duty.xpath('.//li/text()').extract()
        p_require = p_require.xpath('.//li/text()').extract()

        p_duty = '-'.join(p_duty)
        p_require = '-'.join(p_require)

        item['p_name'] = p_name
        item['p_type'] = p_type
        item['p_number'] = p_number.strip('人')
        item['p_location'] = p_location
        item['p_duty'] = p_duty
        item['p_require'] = p_require
        item['crawl_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        item['p_date'] = datetime.now().strftime('%Y-%m-%d')
        item['spider_name'] = self.name

        yield item


# items.py

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

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class Day11Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass



# 定义数据模型
class JobItem(scrapy.Item):
    p_name = scrapy.Field()
    p_type = scrapy.Field()
    p_number = scrapy.Field()
    p_location = scrapy.Field()
    p_date = scrapy.Field()
    p_duty = scrapy.Field()
    p_require = scrapy.Field()
    crawl_time = scrapy.Field()
    spider_name = scrapy.Field()

    def get_sql(self):
        sql = 'insert into py07_tencent_new(p_name,p_type,p_number,p_location,p_date,p_duty,p_require,crawl_time,spider_name) ' \
              'values(%s,%s,%s,%s,%s,%s,%s,%s,%s) on duplicate key update p_number=values(p_number)'
        data = (self['p_name'],self['p_type'],self['p_number'],self['p_location'],self['p_date'],self['p_duty'],self['p_require'],self['crawl_time'],self['spider_name'])

        return sql,data


# pipelines.py

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
import pymysql

class Day11Pipeline(object):
    def process_item(self, item, spider):
        return item


class JobPipeline(object):
    def __init__(self):
        self.f = open('job.json','w',encoding='utf-8')
    def process_item(self,item, spider):
        self.f.write(json.dumps(dict(item),ensure_ascii=False) + '\n')
        return item

    # 爬虫结束调用
    def close_spider(self,spider):
        self.f.close()


class JobMysqlPipeline(object):
    def __init__(self):
        self.conn = pymysql.connect('127.0.0.1','root','123456','han',charset='utf8')
        self.cursor = self.conn.cursor()

    def process_item(self,item,spider):
        # 插入数据库
        sql ,data = item.get_sql()
        self.cursor.execute(sql,data)
        self.conn.commit()

        return item

    def close_spider(self,spider):
        self.cursor.close()
        self.conn.close()
# settings.py

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

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

BOT_NAME = 'day11'

SPIDER_MODULES = ['day11.spiders']
NEWSPIDER_MODULE = 'day11.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'day11 (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

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

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.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)

# 默认是True
# 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',
  # 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'day11.middlewares.Day11SpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html

DOWNLOADER_MIDDLEWARES = {
    # 数字越小 越先经过 范围 1-999
   # 'day11.middlewares.MyCustomDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html

ITEM_PIPELINES = {
   'day11.pipelines.JobPipeline': 1,
   'day11.pipelines.JobMysqlPipeline': 2,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://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 http://scrapy.readthedocs.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'
 
 

# 爬取结果如下:







兄弟连学python


Python学习交流、资源共享群:563626388 QQ



猜你喜欢

转载自blog.csdn.net/fredreck1919/article/details/79883777