Scrapy基于selenium结合爬取淘宝的实例讲解

yipeiwu_com6年前Python爬虫

在对于淘宝,京东这类网站爬取数据时,通常直接使用发送请求拿回response数据,在解析获取想要的数据时比较难的,因为数据只有在浏览网页的时候才会动态加载,所以要想爬取淘宝京东上的数据,可以使用selenium来进行模拟操作

对于scrapy框架,下载器来说已经没多大用,因为获取的response源码里面没有想要的数据,因为没有加载出来,所以要在请求发给下载中间件的时候直接使用selenium对请求解析,获得完整response直接返回,不经过下载器下载,上代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from scrapy.http.response.html import HtmlResponse
from scrapy.http.response.text import TextResponse
from selenium.webdriver import ActionChains
 
class TaobaoMiddleware(object):
 
 #处理请求函数
 def process_request(self,request,spider):
  #声明一个Options对象
  opt = Options()
  #给对象添加一个--headless参数,表示无头启动
  opt.add_argument('--headless')
  #把配置参数应用到驱动创建的对象
  driver = webdriver.Chrome(options=opt)
  #打开requests中的地址
  driver.get(request.url)
 
  #让浏览器滚动到底部
  for x in range(1,11):
   j = x / 10
   js = "document.documentElement.scrollTop = document.documentElement.scrollHeight*%f"%j
   driver.execute_script(js)
   #每次滚动等待0.5s
   time.sleep(5)
 
  #获取下一页按钮的标签
  next_btn =driver.find_element_by_xpath('//span[contains(text(),"下一页")]')
  #睡眠0.5秒
  time.sleep(0.5)
  #对下一页标签进行鼠标右键触发事件
  ActionChains(driver).context_click(next_btn).click().perform()
  # driver.save_screenshot('截图.png')
  #把驱动对象获得的源码赋值给新变量
  page_source = driver.page_source
  #退出
  driver.quit()
 
  #根据网页源代码,创建Htmlresponse对象
  response = HtmlResponse(url=request.url,body=page_source,encoding='utf-8',request=request)
  #因为返回的是文本消息,所以需要指定字符编码格式
 
  return response
 
 def process_response(self,request,response,spider):
 
  return response
 
 def process_exception(self,request,exception,spider):
  pass

以上这篇Scrapy基于selenium结合爬取淘宝的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用正则表达式抓取网页图片的方法示例

本文实例讲述了Python使用正则表达式抓取网页图片的方法。分享给大家供大家参考,具体如下: #!/usr/bin/python import re import urllib #获...

python爬虫selenium和phantomJs使用方法解析

python爬虫selenium和phantomJs使用方法解析

1.selenum:三方库。可以实现让浏览器完成自动化的操作。 2.环境搭建 2.1 安装: pip install selenium 2.2 获取浏览器的驱动程序 下载地址...

python爬虫正则表达式之处理换行符

刚开始学python,记录下问题。 代码如下: #coding:utf-8 import re,urllib2 def getHTML(url): html=urllib2.ur...

python抓取京东价格分析京东商品价格走势

复制代码 代码如下:from creepy import Crawlerfrom BeautifulSoup import BeautifulSoupimport urllib2impo...

python并发爬虫实用工具tomorrow实用解析

tomorrow是我最近在用的一个爬虫利器,该模块属于第三方的一个模块,使用起来非常的方便,只需要用其中的threads方法作为装饰器去修饰一个普通的函数,既可以达到并发的效果,本篇将用...