使用Scrapy爬取动态数据


Posted in Python onOctober 21, 2018

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

网址:

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

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,
}

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

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

使用Scrapy爬取动态数据

至此,程序结束。

下附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

总结

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

Python 相关文章推荐
2款Python内存检测工具介绍和使用方法
Jun 01 Python
解决python3中自定义wsgi函数,make_server函数报错的问题
Nov 21 Python
python读取目录下最新的文件夹方法
Dec 24 Python
Python爬虫——爬取豆瓣电影Top250代码实例
Apr 17 Python
Django发送邮件功能实例详解
Sep 02 Python
分享一个pycharm专业版安装的永久使用方法
Sep 24 Python
Python中zip函数如何使用
Jun 04 Python
python3 中时间戳、时间、日期的转换和加减操作
Jul 14 Python
Python文件名匹配与文件复制的实现
Dec 11 Python
python中实现词云图的示例
Dec 19 Python
python邮件中附加文字、html、图片、附件实现方法
Jan 04 Python
Python快速实现一键抠图功能的全过程
Jun 29 Python
python使用正则表达式来获取文件名的前缀方法
Oct 21 #Python
python遍历文件夹找出文件夹后缀为py的文件方法
Oct 21 #Python
python os.listdir按文件存取时间顺序列出目录的实例
Oct 21 #Python
python查找指定文件夹下所有文件并按修改时间倒序排列的方法
Oct 21 #Python
Python3中关于cookie的创建与保存
Oct 21 #Python
Python3中在Anaconda环境下安装basemap包
Oct 21 #Python
解决安装python库时windows error5 报错的问题
Oct 21 #Python
You might like
smarty的保留变量问题
2008/10/23 PHP
PHP的autoload机制的实现解析
2012/09/15 PHP
2个自定义的PHP in_array 函数,解决大量数据判断in_array的效率问题
2014/04/08 PHP
ThinkPHP中使用ajax接收json数据的方法
2014/12/18 PHP
Linux系统下php获得系统分区信息的方法
2015/03/30 PHP
降低PHP Redis内存占用
2017/03/23 PHP
PHP解析url并得到url参数方法总结
2018/10/11 PHP
PHP7新功能总结
2019/04/14 PHP
学习YUI.Ext 第六天--关于树TreePanel(Part 2异步获取节点)
2007/03/10 Javascript
用js代码改变单选框选中状态的简单实例
2013/12/18 Javascript
jQuery实现tag便签去重效果的方法
2015/01/20 Javascript
通过伪协议解决父页面与iframe页面通信的问题
2015/04/05 Javascript
关于延迟加载JavaScript
2015/05/05 Javascript
jQuery实现将页面上HTML标签换成另外标签的方法
2015/06/09 Javascript
浅谈js控制li标签排序问题 js调用php函数的方法
2016/10/16 Javascript
Node.js连接MongoDB数据库产生的问题
2017/02/08 Javascript
详解Angular5路由传值方式及其相关问题
2018/04/28 Javascript
JavaScript设计模式之装饰者模式定义与应用示例
2018/07/25 Javascript
js的对象与函数详解
2019/01/21 Javascript
使用webpack构建应用的方法步骤
2019/03/04 Javascript
[07:25]DOTA2-DPC中国联赛2月5日Recap集锦
2021/03/11 DOTA
解决python3中解压zip文件是文件名乱码的问题
2018/03/22 Python
python爬取哈尔滨天气信息
2018/07/14 Python
python与caffe改变通道顺序的方法
2018/08/04 Python
利用python Selenium实现自动登陆京东签到领金币功能
2019/10/31 Python
如何利用Python写个坦克大战
2020/11/18 Python
泰国在线书店:SE-ED
2020/06/21 全球购物
消防战士优秀事迹材料
2014/02/13 职场文书
《四季》教学反思
2014/04/08 职场文书
新学期开学标语
2014/06/30 职场文书
护理实习生带教计划
2015/01/16 职场文书
大连导游词
2015/02/12 职场文书
医药公司采购员岗位职责
2015/04/03 职场文书
阿甘正传观后感
2015/06/01 职场文书
导游词之寿县报恩寺
2020/01/19 职场文书
利用Matlab绘制各类特殊图形的实例代码
2021/07/16 Python