python 使用scrapy框架爬取80s电影网电影

您所在的位置:网站首页 80s下载电影的网站 python 使用scrapy框架爬取80s电影网电影

python 使用scrapy框架爬取80s电影网电影

2024-06-08 21:59| 来源: 网络整理| 查看: 265

**思路来自喝口水先**近期的一篇博客 本篇博客适合小白巩固scrapy的使用 scrapy是python非常厉害的一个框架,说实话学了一段时间没有学太明白,视频可以看mooc的嵩天老师的爬虫课程,讲的非常不错,看完之后对scrapy的理解会更加深刻。 本篇博客主要用到了xpath和xpath helper

网页分析

80s电影网链接 首先链接点进去之后,页面会显示出25部电影,我们需要在这个页面找出并拼接出这25部电影的url,然后就是for循环执行重复的操作。 我们随便点开几部电影会发现每个电影的url只有后面一串数字不一样,通过分析用xpath我们可以找到,如图: 在这里插入图片描述

源码

我们有了电影url后,就可以提取我们所需要的信息了 items页面

# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class EightsMovieItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() #电影名称 name = scrapy.Field() #演员 actor = scrapy.Field() #电影的下载链接,可以直接下载 movie_link = scrapy.Field() #图片链接 image_link = scrapy.Field() #电影上映日期 date = scrapy.Field() #电影时长 time_long = scrapy.Field() #电影评分 score = scrapy.Field() #电影简介 introduce = scrapy.Field()

settings页面 主要是加上USER_AGENT其他的大部分是注释就不上代码了 其他的有好多我还没学 spider页面

# -*- coding: utf-8 -*- import scrapy from eights_movie.items import EightsMovieItem from lxml import etree class MovieSpider(scrapy.Spider): name = 'movie' #爬取的地址 start_urls = ['http://www.y80s.com/movie/list'] def parse(self, response): #xpath获取每个电影url的最后一段数字 movie_urls =response.xpath("//ul[@class='me1 clearfix' ]/li/a/@href") for movie_url in movie_urls: #拼接成url生成器返回给回调函数 movie_url = 'http://www.y80s.com/movie/' + str(movie_url.extract()).replace("/movie/","") yield scrapy.Request(movie_url,callback=self.parse_movie) for i in range(2,3): url = 'http://www.y80s.com/movie/list/-----p{}'.format(i) yield scrapy.Request(url, callback=self.parse) def parse_movie(self,response): movie_item = EightsMovieItem() #xpath获取电影名称 movie_item['name'] = str(response.xpath('//*[@id="minfo"]/div[2]/h1/text()'). extract()[0]).replace(" ","").replace("\t","").replace("\n","")[:-6] #获取电影类型 movie_item['actor'] = response.xpath('//div[@class="clearfix"]/span/a/text()').extract()[:3] #电影下载链接 movie_item['movie_link'] = str(response.xpath('//span[@class="xunlei dlbutton3"]/a/@href').extract()[0]) #电影宣传图片 movie_item['image_link'] = str(response.xpath('//div[@class="img"]/img/@src').extract()[0]) #获取上映日期 movie_item['date'] = response.xpath('//div[@class="clearfix"]/span/text()').extract()[-3:-2][0].strip() #获取电影时长 movie_item['time_long'] = response.xpath('//div[@class="clearfix"]/span/text()').extract()[-2:-1][0].strip() #获取电影评分 movie_item['score'] = response.xpath('//div[@style="float:left; margin-right:10px;"]/text()').extract()[1].strip() #获取电影简介 movie_item['introduce'] = str(response.xpath('//span[@id="movie_content"]/text()').extract()[0]).replace("\xa0 ","") yield movie_item

写入csv文件 命令行输入 scrapy crawl name -o xxx.csv就行 name是你的爬虫的名字,xxx是你要保存csv的名字 大概就是这样 写入mongodb数据库 自己探索一下吧也不难

结语

这篇博客非常简单不涉及任何反爬,非常适合刚学完scrapy小试牛刀。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3