python3 + Scrapy爬虫学习之腾讯实战爬取

做了一个非常小,且不是那么完善的项目,目前爬取第一页的职位信息,主要目的是了解scrapy的使用,以及各个文件的配置方法,以后会加以完善。

首先,我们进入腾讯招聘,并搜索python

我们简单获取一下职位名称,职位类别,人数和地点这四项

一:setting.py配置

打开上篇博客创建的项目,并打开settings.py文件,我们需要配置以下几项

1,把这个协议关了

2,设置头部信息,并添加'User-Agent'

3,打开pipelines,300代表优先级,数字越小,优先级越高,我们只有一个piplines,无需设置,用默认的就行

二:items.py编写,我们知道,我们需要四项信息

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

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

import scrapy


class TencentItem(scrapy.Item):
    name = scrapy.Field()
    category = scrapy.Field()
    num = scrapy.Field()
    city = scrapy.Field()

它将把职位名称name,职位分类category,人数num,地址city返回给pipelines处理

三:然后我们编写tencent_spider.py

# -*- coding: utf-8 -*-
import scrapy
from tencent.items import TencentItem

class TencentSpiderSpider(scrapy.Spider):
    name = 'tencent_spider'
    allowed_domains = ['hr.tencent.com']
    start_urls = ['https://hr.tencent.com/position.php?keywords=python&start=0#a']

    def parse(self, response):
        trs = response.xpath("//table[@class='tablelist']//tr")[1:-1]
        for tr in trs:
            tds = tr.xpath(".//td")
            name = tds[0].xpath("./a/text()").get()
            # print(position)
            category = tds[1].xpath("./text()").get()
            # print(category)
            num = tds[2].xpath("./text()").get()
            # print(num)
            city = tds[3].xpath("./text()").get()
            # print(city)
            item = TencentItem(name=name , category=category , num=num , city=city)
            yield item

我们需要导入已经写好的itmes类

from tencent.items import TencentItem

然后我们把开始的url从默认的改成我们需要的,这里爬取第一页的10个职位

start_urls = ['https://hr.tencent.com/position.php?keywords=python&start=0#a']

然后就是xpath语法的运用。

最后,我们把每一项都返还给TencentItem这个类去处理

item = TencentItem(name=name , category=category , num=num , city=city)
yield item

代码中注释内容均为测试代码,可参考

四,pipelines.py

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

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

class TencentPipeline(object):
    def __init__(self):
        self.fp = open("tencet.json" , "w" , encoding="utf-8")

    def open_spider(self, spider):
        pass

    def process_item(self, item, spider):
        #这里返回的item不是字典类型,想要存为json文件,需要转换
        item_json = json.dumps(dict(item),ensure_ascii=False, indent=2)
        self.fp.write(item_json + '\n')
        return item

    def close_spider(self, spider):
        self.fp.close()

首先导入json,在TencentPipeline类中有三个方法,其中open_spider和close_spider在这里用处并不明显,以后会用到,我们还是写一下

设置编码和关闭ascii都是基本操作,我们还可以设置缩进,indent=2

然后要注意代码中的注释内容

最后,我们运行start.py

from scrapy import cmdline

cmdline.execute("scrapy crawl tencent_spider".split())

这样我们就完成了json文件的存储:

以上部分爬取结果。

这是scrapy最基本的运用,简单的保存为本地json文件,后续会继续完善,爬取多页并保存在数据库中。

猜你喜欢

转载自blog.csdn.net/s_kangkang_A/article/details/89162193