2025年4月12日 星期六 乙巳(蛇)年 正月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

爬虫--Scrapy简易爬虫(单页爬取)

时间:08-16来源:作者:点击数:21

1.创建爬虫项目文件 meiju

2.修改settings中爬虫协议为False

3.meiju目录下,再次新建爬虫文件

–scrapy genspider <文件名> <爬虫的url> 这里用meijuSpider文件名

4.主项目下创建快速调试方式

  • 在meijuSpider.py中
  • import scrapy
  • # 爬虫类: 继承scrapy.Spider
  • from ..items import MeijuItem
  • class MeijuspiderSpider(scrapy.Spider):
  • # 爬虫名:唯一
  • name = 'meijuSpider'
  • # 允许的域名列表
  • allowed_domains = ['meijutt.tv']
  • # 第一个爬取的url
  • start_urls = ['https://www.meijutt.tv/new100.html']
  • # 解析响应数据
  • # Scrapy内部爬取完成后自动调用,并返回响应数据
  • def parse(self, response):
  • # print(type(response))
  • # <class 'scrapy.http.response.html.HtmlResponse'>
  • # print(response.text) # 字符串网页内容
  • # print(response.body) # 二进制网页内容
  • # scrapy集成了xpath
  • movie_list = response.xpath('//ul[@class="top-list fn-clear"]/li')
  • # print(movie_list)
  • for movie in movie_list:
  • # 电影名称
  • # m_name = movie.xpath('./h5/a/text()')[0].extract() # 获取data的文本数据
  • # m_name = movie.xpath('./h5/a/text()').extract_first() # 推荐 获取data的文本数据
  • m_name = movie.xpath('./h5/a/text()').get() # 推荐 获取data的文本数据
  • # print(m_name)
  • # 电影类型
  • m_type = movie.xpath('./span[@class="mjjq"]/text()').get()
  • # 电视台
  • m_tv = movie.xpath('./span[@class="mjtv"]/text()').get()
  • # 时间
  • m_time = movie.xpath('./div[@class="lasted-time new100time fn-right"]/font/text()').get()
  • # print(m_name, m_type, m_tv, m_time)
  • # 创建item
  • item = MeijuItem()
  • item["mname"] = m_name # 这里要以字典的方式写
  • item["mtype"] = m_type
  • item["mtv"] = m_tv
  • item["mtime"] = m_time
  • # 这里返回的item会进入到管道piplines中
  • yield item

items.py中

  • import scrapy
  • # item: 一项,项目,数据
  • # 数据模型: 类似Django的Model
  • # 设置爬取哪些字段
  • class MeijuItem(scrapy.Item):
  • mname = scrapy.Field()
  • mtype = scrapy.Field()
  • mtv = scrapy.Field() #定义爬取的字段,上面爬取了名字 类型 时间 tv信息,所以这个定义
  • mtime = scrapy.Field()

在pipelinses.py中

  • class MeijuPipeline:
  • # 需要调用pipline需要做2件事:
  • # 1. 在爬虫文件meijuSpider.py的parse方法中要yield item
  • # 2. 在settings中配置pipline
  • # 会被自动调用多次: 次数取决于meijuSpider中parse方法里yield item的次数
  • def process_item(self, item, spider):
  • # print(f'---- {item} ----')
  • # 存入文件
  • string = str((item['mname'], item['mtype'], item['mtv'], item['mtime']))
  • self.fp.write(string + "\n")
  • self.fp.flush()
  • return item
  • # 在开启爬虫时会自动被调用
  • def open_spider(self, spider):
  • print('开始爬虫...')
  • # 打开文件
  • self.fp = open('meiju_movie.txt', 'a', encoding='utf-8')
  • # 在关闭爬虫时自动调用
  • def close_spider(self, spider):
  • print('爬虫关闭...')
  • # 关闭文件
  • self.fp.close()

在settings.py中

  • ITEM_PIPELINES = {
  • 'meiju.pipelines.MeijuPipeline': 300,
  • } #需要打开这个注释项,不然不能调用pipelines中的类
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐