使用Scrapy爬取动态数据

 更新时间:2018年10月21日 10:31:50   作者:回忆不说话  
今天小编就为大家分享一篇关于使用Scrapy爬取动态数据的文章,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

对于动态数据的爬取,可以选择seleniumPhantomJS两种方式,本文选择的是PhantomJS。

网址:

1.首先第一步,对中间件的设置。

进入pipelines.py文件中:

from selenium import webdriver
from scrapy.http.response.html import HtmlResponse
from scrapy.http.response import Response
class SeleniumSpiderMiddleware(object):
  def __init__(self):
    self.driver = webdriver.PhantomJS()
  def process_request(self ,request ,spider):
    # 当引擎从调度器中取出request进行请求发送下载器之前
    # 会先执行当前的爬虫中间件 ,在中间件里面使用selenium
    # 请求这个request ,拿到动态网站的数据 然后将请求
    # 返回给spider爬虫对象
    if spider.name == 'taobao':
      # 使用爬虫文件的url地址
      spider.driver.get(request.url)
      for x in range(1 ,12 ,2):
        i = float(x) / 11
        # scrollTop 从上往下的滑动距离
        js = 'document.body.scrollTop=document.body.scrollHeight * %f' % i
        spider.driver.execute_script(js)
      response = HtmlResponse(url=request.url,
                  body=spider.driver.page_source,
                  encoding='utf-8',
                  request=request)
      # 这个地方只能返回response对象,当返回了response对象,那么可以直接跳过下载中间件,将response的值传递给引擎,引擎又传递给 spider进行解析
      return response

在设置中,要将middlewares设置打开。

进入settings.py文件中,将

DOWNLOADER_MIDDLEWARES = {
  'taobaoSpider.middlewares.SeleniumSpiderMiddleware': 543,
}

打开。

2.第二步,爬取数据

回到spider爬虫文件中。

引入:

from selenium import webdriver

自定义属性:

def __init__(self):
  self.driver = webdriver.PhantomJS()

查找数据和分析数据:

def parse(self, response):
  div_info = response.xpath('//div[@class="info-cont"]')
  print(div_info)
  for div in div_info:
    title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
    # title = self.driver.find_element_by_class_name("title-row").text
    print('名称:', title)
    price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')

3.第三步,传送数据到item中:

item.py文件中:

name = scrapy.Field()
price = scrapy.Field()

回到spider.py爬虫文件中:

引入:

from ..items import TaobaospiderItem

传送数据:

#创建实例化对象。

item = TaobaospiderItem()
item['name'] = title
item['price'] = price
yield item

在设置中,打开:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

4.第四步,写入数据库:

进入管道文件中。

引入

import sqlite3
写入数据库的代码如下:
class TaobaospiderPipeline(object):
  def __init__(self):
    self.connect = sqlite3.connect('taobaoDB')
    self.cursor = self.connect.cursor()
    self.cursor.execute('create table if not exists taobaoTable (name text,price text)')
  def process_item(self, item, spider):
    self.cursor.execute('insert into taobaoTable (name,price)VALUES ("{}","{}")'.format(item['name'],item['price']))
    self.connect.commit()
    return item
  def close_spider(self):
    self.cursor.close()
    self.connect.close()


在设置中打开:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

因为在上一步,我们已经将管道传送设置打开,所以这一步可以不用重复操作。

然后运行程序,打开数据库查看数据。

至此,程序结束。

下附spider爬虫文件所有代码:

# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from ..items import TaobaospiderItem
class TaobaoSpider(scrapy.Spider):
  name = 'taobao'
  allowed_domains = ['taobao.com']
  start_urls = ['https://s.taobao.com/search?q=%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306']
  def __init__(self):
    self.driver = webdriver.PhantomJS()
  def parse(self, response):
    div_info = response.xpath('//div[@class="info-cont"]')
    print(div_info)
    for div in div_info:
      title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
      print('名称:', title)
      price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')
      item = TaobaospiderItem()
      item['name'] = title
      item['price'] = price
      yield item
  def close(self,reason):
    print('结束了',reason)
    self.driver.quit()

关于scrapy的中文文档:http://scrapy-chs.readthedocs.io/zh_CN/latest/faq.html

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

  • pandas中DataFrame重置索引的几种方法

    pandas中DataFrame重置索引的几种方法

    在pandas中,经常对数据进行处理 而导致数据索引顺序混乱,从而影响数据读取、插入等,所以小编总结了几种索引重置的方法,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • Python脚本实现小猿口算

    Python脚本实现小猿口算

    最近小猿口算已经被不少大学生攻占,一个好好的给小学生的口算题已经变成了大学生的计算机大战,下面我们就来看看如何使用Python脚本就行吧小猿口算
    2024-10-10
  • Python Flask全栈项目实战构建在线书店流程

    Python Flask全栈项目实战构建在线书店流程

    这篇文章主要为大家介绍了Python Flask全流程全栈项目实战之在线书店构建实现过程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • python+Word2Vec实现中文聊天机器人的示例代码

    python+Word2Vec实现中文聊天机器人的示例代码

    本文主要介绍了python+Word2Vec实现中文聊天机器人,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • 用Python徒手撸一个股票回测框架搭建【推荐】

    用Python徒手撸一个股票回测框架搭建【推荐】

    回测框架就是提供这样的一个平台让交易策略在历史数据中不断交易,最终生成最终结果,通过查看结果的策略收益,年化收益,最大回测等用以评估交易策略的可行性。这篇文章主要介绍了用Python徒手撸一个股票回测框架,需要的朋友可以参考下
    2019-08-08
  • Python一行代码对话ChatGPT实现详解

    Python一行代码对话ChatGPT实现详解

    这篇文章主要为大家介绍了Python一行代码对话ChatGPT实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • 教你python 中如何取出colomap部分的颜色范围

    教你python 中如何取出colomap部分的颜色范围

    这篇文章主要介绍了python 中如何取出colomap部分的颜色范围,本文以以jet为例给大家提供一种方法,可以提取colormap色标中的一部分,取出我们满意的色标区域,感兴趣的朋友跟随小编一起看看吧
    2022-02-02
  • Python的爬虫框架scrapy用21行代码写一个爬虫

    Python的爬虫框架scrapy用21行代码写一个爬虫

    最近在学习Python的爬虫框架scrapy,通过爬取线报网站后发现整个过程还是挺值得学习的,所以下面这篇文章主要就给大家介绍了Python的爬虫框架scrapy利用21行代码写一个爬虫的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-04-04
  • python利用 pytesseract快速识别提取图片中的文字((图片识别)

    python利用 pytesseract快速识别提取图片中的文字((图片识别)

    本文介绍了tesseract的python调用,也就是pytesseract库,其中还有一些其他的内容并没有涉及,仅涉及到了图片提取文字,如果你对其感兴趣,可以深入探索一下,也希望能和我探讨一下
    2022-11-11
  • 浅谈flask源码之请求过程

    浅谈flask源码之请求过程

    这篇文章主要介绍了浅谈flask源码之请求过程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07

最新评论