本文主要是介绍python 使用scrapy框架爬取80s电影网电影,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
**思路来自喝口水先**近期的一篇博客
本篇博客适合小白巩固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 etreeclass 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小试牛刀。
这篇关于python 使用scrapy框架爬取80s电影网电影的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!