在前面的二十三章节,我们讲解搭建了Splash的环境,这一章节通过一个实战来讲解Splash的使用。
一、分析页面的数据是否是动态加载的数据
以https://item.jd.com/2600240.html
为例,先使用如下方法查看里面哪些数据是需要动态获取的,执行如下命令。
$ scrapy shell https://item.jd.com/2600240.html
运行结果如下图24-1所示:

再执行view(response)
,如下图24-2。

将会在浏览器打开新页面,如图24-3所示:

从图上的结果可以得知,京东价等信息都是没有显示的,说明这些信息是动态获取的,无法直接通过response.xpath()
方式获取到。
正常情况下的信息如下图24-4所示,京东价为2799.00。

当然,我们也可以使用xpath直接获取下试试能不能拿到这个数据。先用浏览器分析下京东价的HTML的结构,如下图24-5所示。

在shell分别执行如下命令:
response.xpath('//span[@class="p-price"]/span/text()').extract()
response.xpath('//span[@class="p-price"]/span[@class="price J-p-2600240"]/text()').extract()
得到的结果如下图24-6所示:

很明显,我们只能获取到¥
,无法获取到2799.00
,因为2799.00
数据是动态填充的。
二、爬取动态加载的数据
遇到这种动态加载的数据时,不要慌,有很多种解决方法,其中之一就是使用Splash,在使用之前需要搭建Splash环境,具体查看爬虫课堂(二十三)|使用Splash爬取动态页面(1),接下来就是编写具体的代码。完整代码如下:
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from scrapy_splash import SplashMiddleware
from scrapy.http import Request, HtmlResponse
from scrapy.selector import Selector
from scrapy_splash import SplashRequest
class SplashSpider(Spider):
name = 'scrapy_splash'
start_urls = [
'https://item.jd.com/2600240.html'
]
# request需要封装成SplashRequest
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url, self.parse, args={'wait': '0.5'})
def parse(self, response):
# 本文只抓取一个京东链接,此链接为京东商品页面,价格参数是ajax生成的。
site = Selector(response)
# 京东价
prices = site.xpath('//span[@class="p-price"]/span[@class="price J-p-2600240"]/text()').extract()[0]
print '京东价:' + prices
运行 scrapy crawl scrapy_splash
即可。
网友评论