豆瓣有些电影页面需要登录才能查看。

目录

[隐藏

创建工程

scrapy startproject doubanmoive

定义Item

# -*- coding: utf-8 -*-   # Define here the models for your scraped items
# See documentation in:# http://doc.scrapy.org/en/latest/topics/items.html
  from scrapy.itemimport Item, Field     class DoubanmoiveItem(Item):     # define the fields for your item here like:# name = scrapy.Field()     url =Field()#豆瓣链接     name = Field()#电影名     year = Field()#上映年份     score = Field()#分数     vote = Field()#评价人数

编写爬虫(Spider)

在doubanmoive/spiders目录下新建moive_spider.py文件

# -*- coding: utf-8 -*-
from scrapy.selectorimport Selector from scrapy.contrib.spidersimport CrawlSpider,Rule from scrapy.contrib.linkextractors.sgmlimport SgmlLinkExtractor from doubanmoive.itemsimport DoubanmoiveItem   class MoiveSpider(CrawlSpider): 	name="doubanmoive" 	allowed_domains=["movie.douban.com"] 	start_urls=["http://movie.douban.com/top250"] 	rules=[ 		Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/top250\?start=\d+.*'))),     //d+表示数字,至少一个数字, .* 任意数量的不包含换行的字符 		Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/subject/\d+')),callback="parse_item"),]      	def parse_item(self,response): 		sel=Selector(response) 		item=DoubanmoiveItem() 		item['url']= response.url 		item['name']=sel.xpath('//*[@id="content"]/h1/span[1]/text()').extract()        //   //*选取所有元素 		item['year']=sel.xpath('//*[@id="content"]/h1/span[2]/text()').re(r'\((\d+)\)')              //re里的r是什么意思?   		item['score']=sel.xpath('//*[@id="interest_sectl"]/div/p[1]/strong/text()').extract() 		item['vote']=sel.xpath('//*[@id="interest_sectl"]/div/p[2]/a/span/text()').re(r'\d+')
                    return item

代码说明:MoiveSpider继承Scrapy中的CrawlSpider,其中rules稍微复杂一些,定义了URL的抓取规则,符合allow正则表达式的链接都会加入到Scheduler(调度程序)。通过分析豆瓣电影Top250的分页URL

http://movie.douban.com/top250?start=25&filter=&type=可以得到以下规则:

Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/top250\?start=\d+.*'))),

而我们真正要抓取的页面是每一部电影的详细介绍,如《肖申克的救赎》的链接为http://movie.douban.com/subject/1292052/,只有subject后面的数字是变化的,根据正则表达式得到如下代码。

Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/subject/\d+')),callback="parse_item"),

我们需要抓取这种类型链接中的内容,于是加入callback属性,将Response交给parse_item函数来处理。

在parse_item函数中的处理逻辑非常简单,根据一定的规则抓取内容赋给item并返回Item Pipeline。获取大部分标签的内容不需要编写复杂的正则表达式,我们可以使用XPath。

我们可以通过Chrome开发者工具(F12)来获取某内容的XPath表达式,具体操作为在需要抓取的内容上点击审查元素,下方就会出现开发者工具,并定位到该元素,在内容上点击右键,选择复制XPath。注意最好多测试几个页面看看表达式是否是一样的

存储数据

爬虫获取到数据以后我们需要将其存储到数据库中,之前我们提到该操作需要靠项目管道(pipeline)来处理,其通常执行的操作为:

  • 清洗HTML数据
  • 验证解析到的数据(检查项目是否包含必要的字段)
  • 检查是否是重复数据(如果重复就删除)
  • 将解析到的数据存储到数据库中

由于我们获取的数据格式多种多样,有一些存储在关系型数据库中并不方便,可以考虑使用MongoDB。

MySQL不太方便的一点就是需要将数组类型的数据通过分隔符转换。而MongoDB支持存入List、Dict等多种类型的数据。

pipelines.py代码如下:

# -*- coding: utf-8 -*-   # Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html   from scrapy import log from twisted.enterpriseimport adbapi from scrapy.httpimport Request   import MySQLdb import MySQLdb.cursors   class DoubanmoivePipeline(object):     def__init__(self): 		self.dbpool= adbapi.ConnectionPool('MySQLdb', 		db ='scrapy',user='root', 		passwd ='pwd', 		cursorclass = MySQLdb.cursors.DictCursor, 		charset ='utf8', 		use_unicode =False)       def process_item(self, item, spider): 	    query =self.dbpool.runInteraction(self._conditional_insert, item) 	    query.addErrback(self.handle_error)return item       def _conditional_insert(self,tx,item): 	    tx.execute("select * from doubanmoive where m_name= %s",(item['name'][0],))    //可以通过网页的subject数字进行排重。
	    result=tx.fetchone()#log.msg(result,level=log.DEBUG)#print resultif result: 			log.msg("Item already stored in db:%s" % item,level=log.DEBUG)else: 			tx.execute(\ 			"insert into doubanmoive (m_name,m_year,m_score, url, vote) values (%s,%s,%s,%s,%s)",\ 			(item['name'][0],item['year'][0],item['score'][0],item['url'],item['vote'])) 			log.msg("Item stored in db: %s" % item, level=log.DEBUG)       def handle_error(self, e): 			log.err(e)

配置文件

在运行爬虫之前还需要将在settings.py中增加一些配置信息。

# -*- coding: utf-8 -*-   # Scrapy settings for doubanmoive project## For simplicity, this file contains only the most important settings by# default. All the other settings are documented here:##     http://doc.scrapy.org/en/latest/topics/settings.html#   BOT_NAME ='doubanmoive'   SPIDER_MODULES =['doubanmoive.spiders'] NEWSPIDER_MODULE ='doubanmoive.spiders'   ITEM_PIPELINES={'doubanmoive.pipelines.DoubanmoivePipeline':400,} LOG_LEVEL='DEBUG' DOWNLOAD_DELAY =3 RANDOMIZE_DOWNLOAD_DELAY =True USER_AGENT ='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML,like Gecko) Chrome/19.0.1084.54 Safari/536.5'   COOKIES_ENABLED =True
# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = 'doubanmoive (+http://www.yourdomain.com)'

ITEM_PIPELINES中定义了MySQL的 Pipeline文件,后面的数字代表执行的优先级顺序,范围为0~1000。而中间的DOWNLOAD_DELAY等信息是为了防止爬虫被豆瓣禁掉,增加了一些随机延迟,浏览器代理等。

至此,抓取豆瓣电影的爬虫就已经完成了。在命令行中执行scrapy crawl doubanmoive让蜘蛛开始爬行吧!

报错:403

Crawled (403)
HTTP Status Code 403 definitely means Forbidden / Access Denied.
未解决!!
Link extractors are used in the CrawlSpider class 
SgmlLinkExtractor  is now deprecated 
Rule:
 If callback is None follow defaults to True
下面这一行报错:
/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py:187:execute
 query = query % tuple([db.literal(item) for item in args]) 
 <type 'exceptions.TypeError'>: not all arguments converted during string formatting
传参数需要
(item['name'][0],)
Adding the comma at the end of the tuple
'exceptions.IndexError'>: list index out of range
注意xpath存储到item中的类型是
.xpath() and .css() methods return a SelectorList instance, which is a list of new selectors.
列表用[ ]标识。访问时需要用index

print list[0] # 输出列表的第一个元素

艺搜参考

http://www.ituring.com.cn/article/114408

http://www.cnblogs.com/lchd/p/3820968.html

Scrapy爬虫入门系列4抓取豆瓣Top250电影数据的更多相关文章

  1. 基础爬虫,谁学谁会,用requests、正则表达式爬取豆瓣Top250电影数据!

    爬取豆瓣Top250电影的评分.海报.影评等数据!   本项目是爬虫中最基础的,最简单的一例: 后面会有利用爬虫框架来完成更高级.自动化的爬虫程序.   此项目过程是运用requests请求库来获取h ...

  2. Scrapy爬虫入门系列3 将抓取到的数据存入数据库与验证数据有效性

    抓取到的item 会被发送到Item Pipeline进行处理 Item Pipeline常用于 cleansing HTML data validating scraped data (checki ...

  3. requests爬取豆瓣top250电影信息

    ''' 1.爬取豆瓣top250电影信息 - 第一页: https://movie.douban.com/top250?start=0&filter= - 第二页: https://movie ...

  4. Scrapy爬虫入门系列2 示例教程

    本来想爬下http://www.alexa.com/topsites/countries/CN 总排名的,但是收费了 只爬了50条数据: response.xpath('//div[@class=&q ...

  5. 简易数据分析 04 | Web Scraper 初尝--抓取豆瓣高分电影

    这是简易数据分析系列的第 4 篇文章. 今天我们开始数据抓取的第一课,完成我们的第一个爬虫.因为是刚刚开始,操作我会讲的非常详细,可能会有些啰嗦,希望各位不要嫌弃啊:) 有人之前可能学过一些爬虫知识, ...

  6. 抓取豆瓣的电影排行榜TOP100

    #!/usr/bin/env python # -*- coding:utf-8 -*- """ 一个简单的Python爬虫, 用于抓取豆瓣电影Top前100的电影的名称 ...

  7. 爬取豆瓣TOP250电影

    自己跟着视频学习的第一个爬虫小程序,里面有许多不太清楚的地方,不如怎么找到具体的电影名字的,那么多级关系,怎么以下就找到的是那个div呢? 诸如此类的,有许多,不过先做起来再说吧,后续再取去弄懂. i ...

  8. python3下scrapy爬虫(第二卷:初步抓取网页内容之直接抓取网页)

    上一卷中介绍了安装过程,现在我们开始使用这个神奇的框架 跟很多博主一样我也先选择一个非常好爬取的网站作为最初案例,那么我先用屌丝必备网站http://www.shaimn.com/xinggan/作为 ...

  9. python3下scrapy爬虫(第四卷:初步抓取网页内容之抓取网页里的指定数据延展方法)

    上卷中我运用创建HtmlXPathSelector 对象进行抓取数据: 现在咱们再试一下其他的方法,先试一下我得最爱XPATH 看下结果: 直接打印出结果了 我现在就正常拼下路径 只求打印结果: 现在 ...

随机推荐

  1. Less资源汇总

    GUI编译工具 为方便起见,建议初学者使用GUI编译工具来编译.less文件,以下是一些可选GUI编译工具: koala(Win/Mac/Linux) 国人开发的LESSCSS/SASS编译工具.下载 ...

  2. Laravel 5系列教程二:路由,视图,控制器工作流程

    免费视频教程地址https://laravist.com/series/laravel-5-basic 上一篇教程我们走了那么长的路,终于把Laravel安装好了,这一篇教程我们就要进入Laravel ...

  3. html DOM 的继承关系

    零散的知识聚合在一起,就会形成力量,就有了生命力. 如各种语言的开发框架, 都是右各个碎片化的功能聚合在一起,构成有机地整体,便有了强大的力量.will be powerful! 如: jquery ...

  4. mssql性能优化

    总结下SQL SERVER数据库性能优化相关的注意事项,在网上搜索了一下,发现很多文章,有的都列出了上百条,但是仔细看发现,有很多似是而非或者过时(可能对SQL SERVER6.5以前的版本或者ORA ...

  5. [Node.js] Show More Lines in a Node.js Error Stack Trace

    Sometimes you are one or two lines short from finding the cause of the error in the stack trace but ...

  6. Python——Code Like a Pythonista: Idiomatic Python

    Code Like a Pythonista: Idiomatic Python 如果你有C++基础,那学习另一门语言会相对容易.因为C++即面向过程,又面向对象.它很底层,能像C一样访问机器:它也很 ...

  7. Gperftools中tcmalloc的简介和使用(转)

    TcMalloc(Thread-CachingMalloc)是google-perftools工具中的一个内存管理库,与标准的glibc库中malloc相比,TcMalloc在内存分配的效率和速度上要 ...

  8. 【Java】Java_05 标识符与字符集

    1.标识符 用作给变量.类和方法命名.注意: 表示类名的标识符用大写字母开始.如:Man, GoodMan 表示方法和变量的标识符用小写字母开始,后面的描述性词以大写开始.green(),greenC ...

  9. C++常考面试题汇总(持续更新中)

    c++面试题 一 用简洁的语言描述 c++ 在 c 语言的基础上开发的一种面向对象编程的语言: 应用广泛: 支持多种编程范式,面向对象编程,泛型编程,和过程化编程:广泛应用于系统开发,引擎开发:支持类 ...

  10. activiti designer下载地址

    http://www.activiti.org/designer/update/ http://www.activiti.org/designer/archived/       这个地址貌似不能用了 ...