Scrapy Shell调试代码

Scrapy Shell

Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据。

启动Scrapy Shell

进入cmd输入命令行:

scrapy shell "http://quotes.toscrape.com/"

状态码200,表示请求成功。

在爬取一个网站的时候,最好是使用shell来查看下是否有反爬机制,如果返回的状态码不是200,多半是有反爬机制。如果在不知道的前提下强行爬取可能会导致爬虫中断需要登录后才可访问网站,严重的甚至是ip被封。

测试XPath

>>> response.xpath('//div[@class="quote"]//small/text()')
[<Selector xpath='//div[@class="quote"]//small/text()' data='Albert Einstein'>, <Selector xpath='//div[@class="quote"]//small/text()' data='J.K. Rowling'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Albert Einstein'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Jane Austen'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Marilyn Monroe'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Albert Einstein'>, <Selector xpath='//div[@class="quote"]//small/text()' data='André Gide'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Thomas A. Edison'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Eleanor Roosevelt'>, <Selector xpath='//div[@class="quote"]//small/text()' data='Steve Martin'>]
>>> response.xpath('//div[@class="quote"]//small/text()').extract()
['Albert Einstein', 'J.K. Rowling', 'Albert Einstein', 'Jane Austen', 'Marilyn Monroe', 'Albert Einstein', 'André Gide', 'Thomas A. Edison', 'Eleanor Roosevelt', 'Steve Martin']
>>> response.xpath('//div[@class="quote"][1]//small/text()').extract()
['Albert Einstein']
>>> response.xpath('//div[@class="quote"][1]//small/text()').extract()[0]
'Albert Einstein'

以后做数据提取的时候,可以把现在Scrapy Shell中测试,测试通过后再应用到代码中。

猜你喜欢

转载自blog.csdn.net/loner_fang/article/details/81132762
今日推荐