侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python爬虫框架Scrapy实例代码

Python  /  管理员 发布于 7年前   188

目标任务:爬取腾讯社招信息,需要爬取的内容为:职位名称,职位的详情链接,职位类别,招聘人数,工作地点,发布时间。

一、创建Scrapy项目

scrapy startproject Tencent

命令执行后,会创建一个Tencent文件夹,结构如下

二、编写item文件,根据需要爬取的内容定义爬取字段

# -*- coding: utf-8 -*-import scrapyclass TencentItem(scrapy.Item):  # 职位名  positionname = scrapy.Field()  # 详情连接  positionlink = scrapy.Field()  # 职位类别  positionType = scrapy.Field()  # 招聘人数  peopleNum = scrapy.Field()  # 工作地点  workLocation = scrapy.Field()  # 发布时间  publishTime = scrapy.Field()

三、编写spider文件

进入Tencent目录,使用命令创建一个基础爬虫类:

# tencentPostion为爬虫名,tencent.com为爬虫作用范围scrapy genspider tencentPostion "tencent.com"

执行命令后会在spiders文件夹中创建一个tencentPostion.py的文件,现在开始对其编写:

# -*- coding: utf-8 -*-import scrapyfrom tencent.items import TencentItemclass TencentpositionSpider(scrapy.Spider):  """  功能:爬取腾讯社招信息  """  # 爬虫名  name = "tencentPosition"  # 爬虫作用范围  allowed_domains = ["tencent.com"]  url = "http://hr.tencent.com/position.php?&start="  offset = 0  # 起始url  start_urls = [url + str(offset)]  def parse(self, response):    for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):      # 初始化模型对象      item = TencentItem()      # 职位名称      item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]      # 详情连接      item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]      # 职位类别      item['positionType'] = each.xpath("./td[2]/text()").extract()[0]      # 招聘人数      item['peopleNum'] = each.xpath("./td[3]/text()").extract()[0]      # 工作地点      item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]      # 发布时间      item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]      yield item    if self.offset < 1680:      self.offset += 10    # 每次处理完一页的数据之后,重新发送下一页页面请求    # self.offset自增10,同时拼接为新的url,并调用回调函数self.parse处理Response    yield scrapy.Request(self.url + str(self.offset), callback = self.parse)

四、编写pipelines文件

# -*- coding: utf-8 -*-import jsonclass TencentPipeline(object):  """     功能:保存item数据   """  def __init__(self):    self.filename = open("tencent.json", "w")  def process_item(self, item, spider):    text = json.dumps(dict(item), ensure_ascii = False) + ",\n"    self.filename.write(text.encode("utf-8"))    return item  def close_spider(self, spider):    self.filename.close()

五、settings文件设置(主要设置内容)

# 设置请求头部,添加urlDEFAULT_REQUEST_HEADERS = {  "User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;",  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}# 设置item――pipelinesITEM_PIPELINES = {  'tencent.pipelines.TencentPipeline': 300,}

执行命令,运行程序

# tencentPosition为爬虫名scrapy crwal tencentPosition

使用CrawlSpider类改写

# 创建项目scrapy startproject TencentSpider# 进入项目目录下,创建爬虫文件scrapy genspider -t crawl tencent tencent.comitem等文件写法不变,主要是爬虫文件的编写# -*- coding:utf-8 -*-import scrapy# 导入CrawlSpider类和Rulefrom scrapy.spiders import CrawlSpider, Rule# 导入链接规则匹配类,用来提取符合规则的连接from scrapy.linkextractors import LinkExtractorfrom TencentSpider.items import TencentItemclass TencentSpider(CrawlSpider):  name = "tencent"  allow_domains = ["hr.tencent.com"]  start_urls = ["http://hr.tencent.com/position.php?&start=0#a"]  # Response里链接的提取规则,返回的符合匹配规则的链接匹配对象的列表  pagelink = LinkExtractor(allow=("start=\d+"))  rules = [    # 获取这个列表里的链接,依次发送请求,并且继续跟进,调用指定回调函数处理    Rule(pagelink, callback = "parseTencent", follow = True)  ]  # 指定的回调函数  def parseTencent(self, response):    for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):      item = TencentItem()      # 职位名称      item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]      # 详情连接      item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]      # 职位类别      item['positionType'] = each.xpath("./td[2]/text()").extract()[0]      # 招聘人数      item['peopleNum'] = each.xpath("./td[3]/text()").extract()[0]      # 工作地点      item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]      # 发布时间      item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]      yield item

总结

以上所述是小编给大家介绍的Python爬虫框架Scrapy实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!


  • 上一条:
    Python使用Scrapy爬虫框架全站爬取图片并保存本地的实现代码
    下一条:
    详解python中asyncio模块
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客