接上一个例子,通过重写Scrapy框架中是基础爬虫中的方法parse,我们可以获得当前页面中的房源标题和价格等信息,但是如果想要继续获取下一页等信息如何操作?这时候可以用到scrapy中的Request类来完成这个操作。
基本思路:
- 首先,在页面中定位到下一页元素的xpath,获取元素的链接;
- 然后,将获取的链接,重新丢回调度器,并指定回调函数-->使用scrapy.Request类实现。
- 这里面有个小知识点,即需要用到生成器yield,不断的往复如上操作。
# 重写爬取数据函数
def parse(self, response):
# 查看response信息
# print(response)
# 获取页面标题和价格信息
titles = response.xpath('//dl[@class="f-list-item-wrap min-line-height f-clear"]/dd/a/@title').extract()
prices = response.xpath('//span[@class="num"]/text()').extract()
# 打印获取等元素信息
for title, price in zip(titles, prices):
print(title, ': ', price)
# 信息入库操作
gjzf = GanjizufanghzItem()
for title, price in zip(titles, prices):
gjzf['title'] = title
gjzf['price'] = price
yield gjzf
time.sleep(3)
# 获取下一页等链接,并回调进行再次抓取
next_links = response.xpath('//a[@class="next"]/@href').extract()
if len(next_links) > 0:
print('*'*10, next_links[0], '*'*10)
# 使用scrapy等回调函数自动获取下一页链接
# 第一个参数 是 下一页 链接(字符串);第二个是回调函数
yield scrapy.Request(next_links[0], callback=self.parse)
网友评论