CrawlSpiders

时间:2023-03-10 03:11:27
CrawlSpiders

1.用 scrapy 新建一个 tencent 项目

CrawlSpiders

2.在 items.py 中确定要爬去的内容

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

 # Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html import scrapy class TencentItem(scrapy.Item):
# define the fields for your item here like:
# 职位
position_name = scrapy.Field()
# 详情链接
positin_link = scrapy.Field()
# 职业类别
position_type = scrapy.Field()
# 招聘人数
people_number = scrapy.Field()
# 工作地点
work_location = scrapy.Field()
# 发布时间
publish_time = scrapy.Field()

3.快速创建 CrawlSpider模板

scrapy genspider -t crawl tencent_spider tencent.com

注意  此时中的名称不能与项目名相同

4.打开tencent_spider.py 编写代码

 # -*- coding: utf-8 -*-
import scrapy
# 导入链接规则匹配类,用来提取符合规则的链接
from scrapy.linkextractors import LinkExtractor
# 导入CrawlSpider类和Rule
from scrapy.spiders import CrawlSpider, Rule
# 从tentcent项目下的itmes.py中导入TencentItem类
from tencent.items import TencentItem class TencentSpiderSpider(CrawlSpider):
name = 'tencent_spider'
allowed_domains = ['hr.tencent.com']
start_urls = ['http://hr.tencent.com/position.php?&start=0#a']
pagelink = LinkExtractor(allow=("start=\d+")) # 正则匹配 rules = (
# 获取这个列表的链接,依次发送请求,并继续跟进,调用指定的回调函数
Rule(pagelink, callback='parse_item', follow=True),
) def parse_item(self, response):
for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
item = TencentItem()
# 职位名称
item['position_name'] = each.xpath("./td[1]/a/text()").extract()[0]
# 详情连接
item['position_link'] = each.xpath("./td[1]/a/@href").extract()[0]
# 职位类别
#item['position_type'] = each.xpath("./td[2]/text()").extract()[0]
# 招聘人数
item['people_number'] = each.xpath("./td[3]/text()").extract()[0]
# 工作地点
# item['work_location'] = each.xpath("./td[4]/text()").extract()[0]
# 发布时间
item['publish_time'] = each.xpath("./td[5]/text()").extract()[0] yield item

5.在 piplines.py 中写入文件

 1 # -*- coding: utf-8 -*-
2
3 # Define your item pipelines here
4 #
5 # Don't forget to add your pipeline to the ITEM_PIPELINES setting
6 # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
7
8 import json
9
10 class TencentPipeline(object):
11 def open_spider(self, spider):
12 self.filename = open("tencent.json", "w")
13
14 def process_item(self, item, spider):
15 text = json.dumps(dict(item), ensure_ascii = False) + "\n"
16 self.filename.write(text.encode("utf-8")
17 return item
18
19 def close_spider(self, spider):
20 self.filename.close()

7.在命令输入以下命令运行

scrapy crawl tencen_spider.py

出现以下问题在tencent_spider.py 文件中只有把position_type 和 work_location 注销掉才能运行...