zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

011:运用Scrapy爬取腾讯招聘信息

2023-03-15 22:05:05 时间

本章内容为一篇实战项目。不做太多介绍了。直接开始项目描述:

进入官网后

可以看到地址

既是我们需要的地址为

创建Scrapy项目:

tecent_recruit文件夹下找到spiders文件夹, 在此处打开cmd窗口输入命令:scrapy genspider catch_positon tencent.com 创建名为“catch_positon"的爬虫文件

明确爬取目标 我们在pycharm中打开刚才创建好的"tencent_recruit"项目。 找到items.py文件

根据目标网页,我们来确定爬取的目标为

  • “职位名称”、
  • “职位详情连接”、
  • “职位类型”、
  • “招聘人数”、
  • “工作地点”、
  • “发布时间”。

据此,我们来编写“items.py”确定爬取目标。

import scrapy

class TencentRecruitItem(scrapy.Item):
    # define the fields for your item here like:
    position_name = scrapy.Field() #职位名称
    position_detail_link = scrapy.Field() #职位详情链接
    position_type = scrapy.Field() #职位类型
    recruit_num = scrapy.Field() #招聘人数
    work_location = scrapy.Field() #工作地点
    publish_time = scrapy.Field()  #发布时间

编写爬虫文件

双击我们创建好的“catch_positon.py”,来编写爬虫文件。

首先更改“start_urls"字段值为我们的目标网址。

在”settings.py"中将第22行(pycharm中为第22行,不同编辑器可能行数不同)的“ROBOTSTXT_OBEY”协议前加“#“进行注释。

将第19行(pycharm中为第19行,不同编辑器可能行数不同)的”USER_AGENT“前的”#“注释去掉,将其值改为浏览器中用F12看到的值。

然后编写我们爬虫文件catch_positon.py

将parse的内容更改为:

def parse(self, response):
    node_list = response.xpath('//tr[@class="even"]|//tr[@class="odd"]')
    #使用xpath提取数据
    for node in node_list:
        print(node.xpath('./td/a/text()'))

在cmd命令行中输入:scrapy crawl catch_positon运行爬虫进行测试。

可见我们提取到的每行数据列表中只有1个数据,因此我们使用”extract_first()"表示取第一个元素。

注意:"extract()[0]"和“extract_first()"均可取到第一个元素,一旦没有数据时,”extract()[0]“会报错小标范围溢出终止程序运行,而“extract_first()“则会直接返回”null"表示空值,不会打断程序运行,因此,我们在取第一个元素时,我们常用”extract_first()”。

我们导入items的类

将item类实例化,将相应数据赋值给相应的item中。

   def parse(self, response):
        node_list = response.xpath('//tr[@class="even"]|//tr[@class="odd"]')
        #使用xpath提取数据
        for node in node_list:
            item = TencentRecruitItem()
            item['position_name'] = node.xpath('./td[1]/a/text()').extract_first()
            item['position_detail_link']= node.xpath('./td[1]/a/@href').extract_first()
            item['position_type']= node.xpath('./td[2]/text()').extract_first()
            item['recruit_num']= node.xpath('./td[3]/text()').extract_first()
            item['work_location']= node.xpath('./td[4]/text()').extract_first()
            item['publish_time']= node.xpath('./td[5]/text()').extract_first()
            yield item

我们已经成功提取了“腾讯招聘”网的第一页数据。下面,我们来分析网页,爬取全部招聘信息。 按下F12,点击选择元素,选中“下一页”,便可以看到浏览器为我们自动定位的相应网页代码。

我们点击代码中对应的a标签链接,发现直接就来到了第二页。 我们根据这个规律,便可得出爬取全部招聘信息的思路

编写管道文件,存储数据 双击“pipelines.py",进入管道文件,进行编写。

import json
class TencentRecruitPipeline(object):

    def open_spider(self,spider):
        self.file = open('tencent_recruit.json','w',encoding='utf-8')
    def process_item(self, item, spider):
        data = json.dumps(dict(item),ensure_ascii=False)+'
'
        self.file.write(data)
        return item

定义关闭爬虫函数“close_spider”,在爬虫结束时关闭文件。

最后,到“settings.py"中注册管道,找到69行(pycharm中为第69行,不同编辑器可能行数不同),将“ITEM_PIPELINES”对应部分的“#”注释去掉。

至此运行爬虫文件。即可成功实现获取腾讯招聘信息。