scrapy爬取豆瓣top250电影

本文的前提是大家已经安装好了scrapy。如果你们安装好,那就安装吧,根据我的安装经验,如果你使用的是win系统,安装会很麻烦,及时你使用了easyinstall,但是依旧会遇到你不曾想的问题,所以,还是建议使用linux或者mac进行操作吧。

1、使用scrapy创建项目,scrapy startproject DouSpider。创建完成后会产生几个文件,作用分别如下:

  • items.py 模型文件,要采集的内容
  • pipelines.py 将采集的内容进行保存
  • crawal.py 爬虫,爬取内
2、本次我们要爬取的内容主要有: 电影名称、评分、主演等。下面一次编写这几个文件

#items.py
class DouspiderItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field() #电影名称
    bd = scrapy.Field() #背景 导演、上映日期、主演 国别
    value_score = scrapy.Field() #评分
    quote = scrapy.Field()  #主演
#crawal.py
class DouBanSpider(scrapy.Spider):
	name = "DouSpider"
	allowed_domains = ["movie.douban.com"]
	start_urls = [
		"http://movie.douban.com/top250/"
	]
	
	def parse(self,response):
		for info in response.xpath("//div[@class='item']"):
			item = DouspiderItem()
			item['name'] = info.xpath("div[@class='pic']/a/img/@alt").extract()
			item['bd']=info.xpath("div[@class='info']/div[@class='bd']/p[@class='']/text()").extract()
			item['value_score']=info.xpath("div[@class='info']/div[@class='bd']/div[@class='star']/span[@class='rating_num']/text()").extract()
			item['quote']=info.xpath("div[@class='info']/div[@class='bd']/p[@class='quote']/span/text()").extract()
			next_page = response.xpath("//span[@class='next']/a/@href") 
			#print(item['name'],item['bd'],item['value_score'])
			yield item
		if next_page: 
			url = response.urljoin(next_page[0].extract()) 
			yield scrapy.Request(url, self.parse)
#pipelines.py
class DouspiderPipeline(object):
    
    def  __init__(self):
        self.file = codecs.open("data.json","w",encoding="utf-8")
        
    def  CloseSpider():
        self.file.close()
        
    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item

3、上面的代码写完后开始配置,配置文件为:settings.py

DOWNLOADER_MIDDLEWARES = {

    #'DouSpider.middlewares.MyCustomDownloaderMiddleware': 543,

'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,

}

ITEM_PIPELINES = {

    'DouSpider.pipelines.DouspiderPipeline': 300,

}

4、最后,运行爬虫

scrapy runspider DouSpider
结果如下:

5、写在最后:

楼主一直从事C/C++编程,突然有一天,天有异象,飘来几个大字:学习python。所以楼主就开始了漫长的学习之路,目前在学习python数据分析,同时兼职C/C++开发、python运维工具和爬虫开发。如果大家有需求欢迎砸单。也可以关注楼主公众号和微信:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值