转自知乎网
工具和环境
- 语言:python 2.7
- IDE: Pycharm
- 浏览器:Chrome
- 爬虫框架:Scrapy 1.2.1
正文
方法1
通过 scrapy.shell.inspect_response 函数来实现。以上一篇教程的爬虫为例:
# -*- coding: utf-8 -*-
# @Time : 2017/1/7 17:04
# @Author : woodenrobot
from scrapy import Request
from scrapy.spiders import Spider
from scrapyspider.items import DoubanMovieItem
class DoubanMovieTop250Spider(Spider):
name = 'douban_movie_top250'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/'
'537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safar'
'i/537.36',
}
def start_requests(self):
url = 'https://movie.douban.com/top250'
yield Request(url, headers=self.headers)
def parse(self, response):
# 命令行调试代码
from scrapy.shell import inspect_response
inspect_response(response, self)
item = DoubanMovieItem()
movies = response.xpath('//ol[@class="grid_view"]/li')
for movie in movies:
item['ranking'] = movie.xpath(
'.//div[@class="pic"]/em/text()').extract()[0]
item['movie_name'] = movie.xpath(
'.//div[@class="hd"]/a/span[1]/text()').extract()[0]
item['score'] = movie.xpath(
'.//div[@class="star"]/span[@class="rating_num"]/text()'
).extract()[0]
item['score_num'] = movie.xpath(
'.//div[@class="star"]/span/text()').re(ur'(\d+)人评价')[0]
yield item
next_url = response.xpath('//span[@class="next"]/a/@href').extract()
if next_url:
next_url = 'https://movie.douban.com/top250' + next_url[0]
yield Request(next_url, headers=self.headers)
我们在下载完网页源码进行解析前可以插入上述两句代码,在命令行运行爬虫出现以下效果:
![](https://pic3.zhimg.com/80/v2-8cc13876c3f6433de7faadca58719c56_hd.jpg)
![](https://pic2.zhimg.com/80/v2-7d6fe80723de185d5600a30d6df7e713_hd.jpg)
![](https://pic4.zhimg.com/80/v2-bf7fe43b27b429e1d573d02692968c30_hd.jpg)
![](https://pic1.zhimg.com/80/v2-f800b2a2724a7b95a544809c2a4de676_hd.jpg)
方法2
首先在setting.py同级目录下创建run.py文件。
![](https://pic1.zhimg.com/80/v2-398c55251db4d40f34d59e34c2d8f0ac_hd.jpg)
写入以下代码:
# -*- coding: utf-8 -*-
# @Time : 2017/1/1 17:51
# @Author : woodenrobot
from scrapy import cmdline
name = 'douban_movie_top250'
cmd = 'scrapy crawl {0}'.format(name)
cmdline.execute(cmd.split())
其中name参数为spider的name。
接着在spider文件中设置断点。
![](https://pic1.zhimg.com/80/v2-0e77288f5bd98932c3d5807151a4b6d2_hd.jpg)
![](https://pic2.zhimg.com/80/v2-2af7bcc093f437260a8003e9a630c7a3_hd.jpg)
![](https://pic3.zhimg.com/80/v2-b75aeab369e0358a41aa135d862fa7c8_hd.jpg)
结语
两种方法适合不同的场景,不过一般情况下肯定是方法2好用。