一、介绍
个人最近学习scrapy的一个练手项目,因为是爬取静态网页比较简单,不过还是基本熟悉了用scrapy进行爬虫的流程。爬取的是豆瓣top250的电影名称,导演,评分等。
二、代码解析
-
首先创建初始爬虫项目, cd到想保存的目录,然后在命令行中输入
$ scrapy startproject top250
-
然后我们开始更改item.py文件,代码如下
import scrapy
class Top250Item(scrapy.Item):
movie_name = scrapy.Field()
director = scrapy.Field()
actor = scrapy.Field()
type = scrapy.Field()
score = scrapy.Field() -
pipeline不用修改,但我们需要修改setting
BOT_NAME = 'top250'
SPIDER_MODULES = ['top250.spiders']
NEWSPIDER_MODULE = 'top250.spiders'
FEED_URI = './TOP250.csv' # 输入保存的位置
FEED_FORMAT = 'csv' # 保存为csv格式
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' # 在google里输入‘what is my user agent’就可以找到 -
下面就要开始正式的工作了,我们在spiders文件夹下创建一个名为mySpider.py的文件,然后输入以下代码
# -*- coding:utf-8 -*-
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy.selector import Selector
from top250.items import Top250Item
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import re
class mySpider(CrawlSpider):
name = 'movies' # 爬虫名
download_delay = 1 # 设置下载延迟
allowed_domains = ['movie.douban.com'] #允许爬取的主域名
start_urls =["https://movie.douban.com/top250"] #开始爬取的地址
rules = [Rule(LinkExtractor(allow=(r'https://movie.douban.com/top250\?start=\d+.*'))),
Rule(LinkExtractor(allow=(r'https://movie.douban.com/subject/\d+')), callback='parse_item', follow=False)]
#设置爬取的规则
def parse_item(self, response): #自定义网页解析
sel = Selector(response)
item = Top250Item()
#利用xpath表达式来进行内容的提取,.加入encode('GBK')的作用是防止中文在csv中显示为乱码。
item['movie_name'] = [m.encode('GBK') for m in sel.xpath('//*[@id="content"]/h1/span[1]/text()').extract()]
item['director'] = [m.encode('GBK') for m in sel.xpath('//*[@id="info"]/span[1]/span[2]/a/text()').extract()]
item['actor'] = [m.encode('GBK') for m in sel.xpath('//*[@id="info"]/span[3]/span[2]/a/text()').extract()]
item['type'] = [m.encode('GBK') for m in sel.xpath('//*[@id="info"]/span[6]/text()').extract()]
item['score'] = sel.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()').extract()
yield item介绍一个chrome中很好用的工具,可以自动帮你写出xpath表达式
。用法是将需要提取的元素拉黑选定,点击右键,选择‘检查’,然后在相应的代码位置点击右键,选择‘copy -> copy xpath’即可 -
运行爬虫
cd到项目的目录,在命令行中输入
scrapy crawl movies
最后爬取的效果如图所示