Python3-Scrapy框架-猎聘网

进入网站首页:
找到如下所示位置,可得到对应页面的信息(在链接页面上方不能进行条件筛选,否则需要进行页面测试能否爬虫)

一.创建项目

这里默认已经安装好了Python、Scrapy等环境

1.打开cmd创建项目
scrapy startproject liepincom

在这里插入图片描述

2.进入项目目录

cd liepincom
在这里插入图片描述

3. 创建spider
scrapy genspider liepin liepin.com

在这里插入图片描述
命令执行完毕后,项目的目录结构应该如下述所示:
在这里插入图片描述

4.导入第三方库

本人安装的第三方库如下所示,当然对于本项目来说是有多余的,为了供大家方便使用,现将全部内容展现出来供大家安装使用。

操作方法:将下述内容复制到文本文件中,并重命名为requirements(这种命名是一种规范,一目了然,当然了想起别的名称也没问题)

async-generator==1.10
attrs==22.1.0
Automat==22.10.0
certifi==2022.9.24
cffi==1.15.1
charset-normalizer==2.1.1
constantly==15.1.0
cryptography==38.0.4
cssselect==1.2.0
et-xmlfile==1.1.0
exceptiongroup==1.0.4
filelock==3.8.2
h11==0.14.0
hyperlink==21.0.0
idna==3.4
incremental==22.10.0
itemadapter==0.7.0
itemloaders==1.0.6
jmespath==1.0.1
lxml==4.9.1
openpyxl==3.0.10
outcome==1.2.0
packaging==21.3
parsel==1.7.0
Protego==0.2.1
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycparser==2.21
PyDispatcher==2.0.6
PyMySQL==1.0.2
pyOpenSSL==22.1.0
pyparsing==3.0.9
pyquery==1.4.3
PySocks==1.7.1
queuelib==1.6.2
requests==2.28.1
requests-file==1.5.1
Scrapy==2.7.1
selenium==4.7.2
service-identity==21.1.0
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
tldextract==3.4.0
trio==0.22.0
trio-websocket==0.9.2
Twisted==22.10.0
twisted-iocpsupport==1.0.2
typing-extensions==4.4.0
urllib3==1.26.13
w3lib==2.1.0
wsproto==1.2.0
zope.interface==5.5.2

此时项目分支展示:
在这里插入图片描述

保存完文件,最后执行如下命令
在这里插入图片描述
环境配置成功!

二、编写spider代码

修改liepin.py代码如下所示:

import scrapy
from scrapy import Selector
from liepincom.items import LiepincomItem


class LiepinSpider(scrapy.Spider):
    name = 'liepin'
    allowed_domains = ['liepin.com']
    start_urls = ['https://liepin.com/career/java']

    # 预先准备好待爬取页面的URL
    def start_requests(self):
        for page in range(5):
            yield scrapy.Request(
                url=f'https://www.liepin.com/career/java/pn{
      
      page}/'
            )


    def parse(self, response):
        sel = Selector(response)
        # 用不同的xpath路径方式进行解析,多体会xpath解析方式的强大与方便之处
        position = sel.xpath('/html/body/div/div/div/div[1]/div/div[1]/ul/li/div/div/div[1]/div/a[1]/div[1]/div/div[1]/text()').extract()  # 完整路径
        city = sel.xpath('//div[@class="job-title-box"]//span[@class="ellipsis-1"]/text()').extract()  #手写xpath路径
        salary = sel.xpath('//*[@id="main-container"]/div/div/div[1]/div/div[1]/ul/li/div/div/div/div/a/div[1]/span/text()').extract()  # 浏览器给出的路径
        year = sel.xpath('//*[@id="main-container"]/div/div/div[1]/div/div[1]/ul/li/div/div/div[1]/div/a[1]/div[2]/span[1]/text()').extract()
        edu = sel.xpath('//*[@id="main-container"]/div/div/div[1]/div/div[1]/ul/li/div/div/div[1]/div/a[1]/div[2]/span[2]/text()').extract()
        company = sel.xpath('//div[@data-nick="job-detail-company-info"]//div[@class="job-company-info-box"]/span/text()').extract()
        company_size = sel.xpath('//div[@data-nick="job-detail-company-info"]//div[@class="company-tags-box ellipsis-1"]//span[last()]/text()').extract()

        for a, b, c, d, e, f, g in zip(position,city,salary,year,edu,company,company_size):
            liepin_item = LiepincomItem()
            liepin_item['position'] = a
            liepin_item['city'] = b
            liepin_item['salary'] = c
            liepin_item['year'] = d
            liepin_item['edu'] = e
            liepin_item['company'] = f
            liepin_item['company_size'] = g
            # 注意不要用return,否则遍历一次就返回完毕了
            yield liepin_item

三、编写items数据结构对象

修改items.py代码如下所示:

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

import scrapy

class LiepincomItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    position = scrapy.Field()
    city = scrapy.Field()
    salary = scrapy.Field()
    year = scrapy.Field()
    edu = scrapy.Field()
    company = scrapy.Field()
    company_size = scrapy.Field()

四、编写Pipelines项目管道

修改pipelines.py代码如下所示:

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


# useful for handling different item types with a single interface
import openpyxl
import pymysql
from itemadapter import ItemAdapter

# 保存数据到Mysql数据库
class MysqlPipeline:

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',port=3306,
                                    user='root',password='1234',
                                    database='spider')
        self.cursor = self.conn.cursor()

    def close_spider(self,spider):
        self.conn.commit()
        self.conn.close()

    # 回调函数,让scrapy框架主动调用我们的方法(callback),上述其他方法都是调用框架给我们的方法(call),每有一个数据就调用一次
    def process_item(self, item, spider):
        db_post = item.get('position', '')
        db_city = item.get('city', '')
        db_salary = item.get('salary', '')
        db_year = item.get('year', '')
        db_edu = item.get('edu', '')
        db_company = item.get('company', '')
        db_company_size = item.get('company_size', '')

        self.cursor.execute(
            'insert into liepin_zhaopin (position, city, salary, year, edu, company, company_size) values (%s,%s,%s,%s,%s,%s,%s)',
            (db_post, db_city, db_salary, db_year, db_edu, db_company, db_company_size)
        )
        return item


# 保存数据到excel
class LiepincomPipeline:

    def __init__(self):
        # 创建工作簿
        self.wb = openpyxl.Workbook()
        # 拿到默认被激活的工作表
        self.ws = self.wb.active
        self.ws.title = '招聘信息'
        self.ws.append(('岗位','城市','薪水','工作年限','学历','公司名称','公司规模'))

    def close_spider(self,spider):
        self.wb.save('招聘数据.xlsx')

    # 回调函数,让scrapy框架主动调用我们的方法(callback),上述其他方法都是调用框架给我们的方法(call)
    def process_item(self, item, spider): # 得到数据并写入excel文件中
        db_post = item.get('position','')
        db_city = item.get('city','')
        db_salary = item.get('salary','')
        db_year = item.get('year','')
        db_edu = item.get('edu','')
        db_company = item.get('company','')
        db_company_size = item.get('company_size','')
        self.ws.append((db_post, db_city, db_salary, db_year, db_edu, db_company, db_company_size))
        return item

五、修改一些settings配置信息

注意:数字越小,越靠前执行

ITEM_PIPELINES = {
    
    
   'liepincom.pipelines.LiepincomPipeline': 300,
   'liepincom.pipelines.MysqlPipeline': 200,
}

六、创建数据库表

这里是在Navicat中执行了如下命令,先创建数据库,再创建张表

CREATE DATABASE spider
CREATE TABLE `liepin_zhaopin`(
`liepin_id` int UNSIGNED auto_increment comment '编号',
`position` VARCHAR(50) not null comment '岗位',
`city` VARCHAR(30) not null COMMENT '城市',
`salary` VARCHAR(30) not null COMMENT '薪水',
`year` VARCHAR(30) not NULL COMMENT '工作年限',
`edu` VARCHAR(20) not NULL COMMENT '学历',
`company` VARCHAR(50) not NULL COMMENT '公司',
`company_size` VARCHAR(30) not NULL COMMENT '公司规模',
PRIMARY KEY (`liepin_id`)
)

可以发现,数据库中有了对应的表
在这里插入图片描述

七、执行程序

进入到项目文件夹,输入如下命令,回车
在这里插入图片描述
在Mysql数据库生成如下数据:
在这里插入图片描述

并在项目目录下生成了如下文件:

打开后内容展示

八、项目说明

1.如上内容爬取的是java相关信息,如想爬取其他,只需更改URL链接地址即可,因为页面的构造相同,xpath解析路径没有发生改变。
2.因为网站robots协议设置关系,不是所有页面都可以进行爬取的,关于能够爬取哪些页面,可以通过如下方式查看:
以Edge浏览器为例,打开F12开发者模式,找到网络–>全部–>预览,刷新;
如果这里预览到了页面的全部信息,说明是可以进行直接爬取的;否则,需要改进技术选型和方法,应对此种问题的方式这里先不做介绍。
3.后续改进,可以遍历首页中的列表进入子链接URL,重复调用parse方法,如此操作,所有岗信息都可以进行一次爬取了(即不用再更改网页URL后重复执行程序了)。

猜你喜欢

转载自blog.csdn.net/weixin_52323239/article/details/128260442