51Testing软件测试论坛

标题: python scrapy 腾讯社会招聘爬虫摘要 [打印本页]

作者: 姿态    时间: 2019-3-25 14:29
标题: python scrapy 腾讯社会招聘爬虫摘要
一 . 编写scrapy爬虫

创建项目:D:\scrapy>scrapy startproject Tencent
D:\scrapy> cd Tentcent
创建爬虫:D:\scrapy\Tentcent>scrapy genspider tencent hr.tencent.com
# 腾讯社招 https://hr.tencent.com/position.php?&start=0#a
职位名 positionName

职位详情连接 positionLink

职位类别  positionType

招聘人数  peopleNumber

工作地点  workLocation

发布时间  publishTime
scrapy启动,会先读取配置文件 setting.py

编写items.py,明确需要提取的数据。

编写spiders/xxxx.py爬虫文件,处理请求和响应,以及提取数据(yield item)。

编写pipelines.py,编写管道文件,处理spider返回item数据。

编写setting.py, 启动管道文件,以及其他相关设置

执行爬虫,调试等。



二 、配置mysql数据库

1. 安装pymysql

cmd下:pip install pymysql
然后python >>> import pymysql 检查是否安装完成,安装成功!


2. 查看items.py

  1. class TencentItem(scrapy.Item):
  2.     # name = scrapy.Field()
  3.     # 职位名
  4.     positionName = scrapy.Field()
  5.     # 职位详情连接 
  6.     positionLink = scrapy.Field()
  7.     # 职位类别
  8.     positionType = scrapy.Field()
  9.     # 招聘人数
  10.     peopleNumber = scrapy.Field()
  11.     # 工作地点
  12.     workLocation = scrapy.Field()
  13.     # 发布时间
  14.     publishTime = scrapy.Field()
复制代码

3. 创建数据库和表
  1. mysql> create database tencent DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
  2. mysql> use tencent;

  3. CREATE TABLE `hr` (
  4. `id`  int(10) NOT NULL ,
  5. `positionName`  varchar(100) NOT NULL COMMENT '职位名' ,
  6. `positionLink`  varchar(150) NULL DEFAULT  COMMENT '职位详情连接' ,
  7. `positionType`  varchar(30) NULL COMMENT '职位类别' ,
  8. `peopleNumber`  int(10) NULL COMMENT '招聘人数' ,
  9. `workLocation`  varchar(30) NULL COMMENT '工作地点' ,
  10. `publishTime`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '发布时间' ,
  11. PRIMARY KEY (`id`)
  12. );
复制代码

4. setting.py
  1. ITEM_PIPELINES = {
  2.    #'Tencent.pipelines.TencentPipeline': 300,
  3.    'Tencent.pipelines.TencentMysqlDBPipeline': 200,
  4. }

  5. #Mysql数据库的配置信息
  6. MYSQL_HOST = '127.0.0.1'
  7. MYSQL_DBNAME = 'tencent'
  8. MYSQL_USER = 'root'
  9. MYSQL_PASSWD = ''
  10. MYSQL_PORT = 3306
复制代码

5. pipelines.py
  1. # import json
  2. import pymysql
  3. # from scrapy.conf import settings
  4. from scrapy import log
  5. from twisted.enterprise import adbapi


  6. class TencentMysqlDBPipeline(object):
  7.     @classmethod
  8.     def from_settings(cls, settings):
  9.         dbargs = dict(
  10.             host=settings['MYSQL_HOST'],
  11.             db=settings['MYSQL_DBNAME'],
  12.             user=settings['MYSQL_USER'],
  13.             passwd=settings['MYSQL_PASSWD'],
  14.             port=settings['MYSQL_PORT'],
  15.             charset='utf8',
  16.             cursorclass=pymysql.cursors.DictCursor,
  17.             use_unicode=True,
  18.         )
  19.         dbpool = adbapi.ConnectionPool('pymysql', **dbargs)
  20.         return cls(dbpool)


  21.     def __init__(self,dbpool):
  22.         self.dbpool=dbpool

  23.     #pipeline默认调用
  24.     def process_item(self, item, spider):
  25.         d=self.dbpool.runInteraction(self._conditional_insert, item, spider) #调用插入的方法
  26.         log.msg("-------------------连接好了-------------------")
  27.         d.addErrback(self._handle_error,item,spider) #调用异常处理方法
  28.         d.addBoth(lambda _: item)
  29.         return d

  30.     def _conditional_insert(self, conn, item, spider):
  31.         log.msg("-------------------打印-------------------")

  32.         conn.execute("insert into hr (positionName, positionLink, positionType, peopleNumber, workLocation, publishTime) values(%s, %s, %s, %s, %s, %s)",
  33.                      (item['positionName'], item['positionLink'], item['positionType'], item['peopleNumber'], item['workLocation'], item['publishTime']))
  34.         log.msg("-------------------一轮循环完毕-------------------")
  35.     def _handle_error(self, failue, item, spider):
  36.         print(failue)
复制代码

6. spiders/tencent.py
  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from Tencent.items import TencentItem
  4. # https://hr.tencent.com/position.php?&start=0#a

  5. class TencentSpider(scrapy.Spider):
  6.     name = 'tencent'
  7.     allowed_domains = ['tencent.com']
  8.     baseURL = 'https://hr.tencent.com/position.php?&start='
  9.     offset = 0
  10.     start_urls = [baseURL + str(offset)]


  11.     def parse(self, response):
  12.         node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']")
  13.         for node in node_list:
  14.             item = TencentItem()                # encode("utf-8") 将字符串从unicode转换到utf-8
  15.             item['positionName'] = node.xpath("./td[1]/a/text()").extract()[0].encode("utf-8")
  16.             item['positionLink'] = ("https://hr.tencent.com/" + node.xpath("./td[1]/a/@href").extract()[0]).encode("utf-8")
  17.             if(len(node.xpath("./td[2]/text()"))):
  18.                 item['positionType'] = node.xpath("./td[2]/text()").extract()[0].encode("utf-8")
  19.             else:
  20.                 item['positionType'] = "无类别".encode("utf-8")
  21.             item['peopleNumber'] = node.xpath("./td[3]/text()").extract()[0].encode("utf-8")
  22.             item['workLocation'] = node.xpath("./td[4]/text()").extract()[0].encode("utf-8")
  23.             item['publishTime']  = node.xpath("./td[5]/text()").extract()[0].encode("utf-8")

  24.             # yield 是返回数据后还能回来接着执行代码
  25.             yield item

  26.         # 第二种方法,提取下一页,爬去全部页面
  27.         #  如果xpath取不到值 ==0  就不是最终页
  28.         if len(response.xpath("//a[@class='noactive' and @id='next']")) == 0:
  29.             nextUrl = "https://hr.tencent.com/" + response.xpath("//a[@id='next']/@href").extract()[0]
  30.             yield scrapy.Request(nextUrl, callback=self.parse)

  31.         # 第一种方法:指定爬取页数
  32.         # if self.offset < 3980:
  33.         #     self.offset += 10
  34.         #     url = self.baseURL + str(self.offset)
  35.         #     #scrapy.Request(url, callback=self.parse_next)
  36.         #     yield scrapy.Request(url, callback=self.parse)

  37.     # #def parse_next(self,response):
  38.     #     #pass
复制代码




作者: Miss_love    时间: 2021-1-5 14:53
支持




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2