爬虫框架Scrapy-爬取前程无忧岗位名称

1. Scrapy学习网站:

http://www.scrapyd.cn/doc/160.html 中文Scrapy
https://docs.scrapy.org/en/latest/intro/install.html 英文Scrapy

2.利用Scrapy 框架爬取前程无忧数据

  • 1)建立工程:scrapy startproject +project name

    实例步骤:

    • win+R ->输入cmd
    • cd 定位到你创建项目的路径,我创建到E:\C盘数据
    • 创建项目:scrapy startproject paqu_project,回车会发现路径下出现一个叫paqu_project的文件夹。
      爬虫框架Scrapy-爬取前程无忧岗位名称_第1张图片
      爬虫框架Scrapy-爬取前程无忧岗位名称_第2张图片

    2)创建爬虫spider:scrapy scrapy genspider aa aa.com

    实例步骤:

    • 路径改为新建项目spider路径:E:\C盘数据\paqu_project\paqu_project\spiders
    • 创建项目:scrapy genspider jobs.51job jobs.51job.com
      爬虫框架Scrapy-爬取前程无忧岗位名称_第3张图片爬虫框架Scrapy-爬取前程无忧岗位名称_第4张图片爬虫框架Scrapy-爬取前程无忧岗位名称_第5张图片

    3)修改jobs_51job.py

# -*- coding: utf-8 -*-
#http://www.scrapyd.cn/doc/147.html  中文介绍Scrap
#https://www.jb51.net/article/131731.htm  介绍方面
#https://zhuanlan.zhihu.com/p/113371985   Python爬虫框架Scrapy的安装与正确使用方法
import scrapy
class QianwuyouItem(scrapy.Item): #这个本来是定义在items.py里面,但是调用库出现问题,我直接在此处定义
    # define the fields for your item here like:
    name = scrapy.Field()
    name_1=scrapy.Field()
    pass
class Jobs51jobSpider(scrapy.Spider):
    name = 'jobs.51job'   #爬取spider的名称
    start_urls = ['https://jobs.51job.com/beijing/p1/']  #爬取的网页
    def parse(self, response):
        #利用xpath爬取岗位名称,其他的可以自行添加
        name=response.xpath('/html/body/div[4]/div[2]/div[1]/div[2]/div/p[1]/span[1]/a/@title').getall()
        #next_page:下一页的url,如果存在,则爬取下一页,如果不存在,则结束
        next_page=response.xpath('/html/body/div[4]/div[2]/div[1]/div[4]/div/div/div/ul/li[6]/a/@href').get()
        for i in name:
            name_1=i
            filename="text.txt"   #定义保存文件名称格式
            with  open(filename,"a+") as f:
                f.write(i)         #写入一行
                f.write('\n')      #回车,换行
                f.close()          #关闭文件
        if next_page is not None:
            next_page=response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

4)运行spider:scrapy crawl +name,即scrapy crawl jobs.51job

运行过程截图:
爬虫框架Scrapy-爬取前程无忧岗位名称_第6张图片爬虫框架Scrapy-爬取前程无忧岗位名称_第7张图片

5)总结:

爬虫框架Scrapy-爬取前程无忧岗位名称_第8张图片

1)页面有5069,运行时间有点长,可以对页面数进行改进,比如:爬取1000页停止或者不存在下一页。
2)本例题只爬取了1个属性,大家可以尝试爬取多个属性。
喜欢的给个小关注:
爬虫框架Scrapy-爬取前程无忧岗位名称_第9张图片

你可能感兴趣的:(爬虫入门,python)