练习:一只豆瓣电影TOP250爬虫
练习:一只豆瓣电影TOP250爬虫
①创建project
②编辑items.py
import scrapy
class DoubanmovieItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() rank = scrapy.Field() title = scrapy.Field() link = scrapy.Field() rate = scrapy.Field() quote = scrapy.Field()
③创建douban_spider.py
import scrapyfrom doubanmovie.items import DoubanmovieItem
class DoubanSpider(scrapy.Spider): """docstring for Movie250Spider""" name = ‘doubanmovie‘ allowed_domains = ["douban.com"] start_urls = [ "http://movie.douban.com/top250/" ]
def parse(self, response): for info in response.xpath(‘//div[@class="item"]‘): item = DoubanmovieItem() item[‘rank‘] = info.xpath(‘div[@class="pic"]/em/text()‘).extract() item[‘title‘] = info.xpath(‘div[@class="pic"]/a/img/@alt‘).extract() item[‘link‘] = info.xpath(‘div[@class="pic"]/a/@href‘).extract() item[‘rate‘] = 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() yield item
# 翻页 next_page = response.xpath(‘//span[@class="next"]/a/@href‘) if next_page: url = response.urljoin(next_page[0].extract()) yield scrapy.Request(url, self.parse)
关于xpath的查找,之前有说过,可以使用xpath checker这个插件,也可以直接使用审查元素
我们要找的内容就在<div class="item"></div>
之内,所以得先声明在这之内查找//div[@class="item"]
如查找rank
那么rank就在<div class="pic">
下的<em class=""></em>
之中,于是就写成div[@class="pic"]/em/text()
④运行,生成csv文件
[KANO@kelvin doubanmovie]$ scrapy crawl doubanmovie -o items.csv
最后的文件夹内容如下
打开items.csv文件查看内容
另外,如果需要,还可以在settings.py文件中加入user-agent
BOT_NAME = ‘doubanmovie‘
SPIDER_MODULES = [‘doubanmovie.spiders‘]NEWSPIDER_MODULE = ‘doubanmovie.spiders‘
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‘
△注意,一定要记得先声明
# -*- coding: utf-8 -*-
否则运行会出错!!!
时间: 2024-11-08 19:15:33