使用Scrapy爬取動態(tài)數(shù)據(jù)
對于動態(tài)數(shù)據(jù)的爬取,可以選擇selenium和PhantomJS兩種方式,本文選擇的是PhantomJS。
網(wǎng)址:
1.首先第一步,對中間件的設(shè)置。
進入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):
# 當(dāng)引擎從調(diào)度器中取出request進行請求發(fā)送下載器之前
# 會先執(zhí)行當(dāng)前的爬蟲中間件 ,在中間件里面使用selenium
# 請求這個request ,拿到動態(tài)網(wǎng)站的數(shù)據(jù) 然后將請求
# 返回給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對象,當(dāng)返回了response對象,那么可以直接跳過下載中間件,將response的值傳遞給引擎,引擎又傳遞給 spider進行解析
return response
在設(shè)置中,要將middlewares設(shè)置打開。
進入settings.py文件中,將
DOWNLOADER_MIDDLEWARES = {
'taobaoSpider.middlewares.SeleniumSpiderMiddleware': 543,
}
打開。
2.第二步,爬取數(shù)據(jù)
回到spider爬蟲文件中。
引入:
from selenium import webdriver
自定義屬性:
def __init__(self): self.driver = webdriver.PhantomJS()
查找數(shù)據(jù)和分析數(shù)據(jù):
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.第三步,傳送數(shù)據(jù)到item中:
在item.py文件中:
name = scrapy.Field() price = scrapy.Field()
回到spider.py爬蟲文件中:
引入:
from ..items import TaobaospiderItem
傳送數(shù)據(jù):
#創(chuàng)建實例化對象。
item = TaobaospiderItem() item['name'] = title item['price'] = price yield item
在設(shè)置中,打開:
ITEM_PIPELINES = {
'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}
4.第四步,寫入數(shù)據(jù)庫:
進入管道文件中。
引入
import sqlite3
寫入數(shù)據(jù)庫的代碼如下:
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()
在設(shè)置中打開:
ITEM_PIPELINES = {
'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}
因為在上一步,我們已經(jīng)將管道傳送設(shè)置打開,所以這一步可以不用重復(fù)操作。
然后運行程序,打開數(shù)據(jù)庫查看數(shù)據(jù)。

至此,程序結(jié)束。
下附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('結(jié)束了',reason)
self.driver.quit()
關(guān)于scrapy的中文文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/faq.html
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- python使用scrapy發(fā)送post請求的坑
- Python爬蟲框架scrapy實現(xiàn)downloader_middleware設(shè)置proxy代理功能示例
- Python爬蟲框架scrapy實現(xiàn)的文件下載功能示例
- python爬蟲框架scrapy實現(xiàn)模擬登錄操作示例
- Python下使用Scrapy爬取網(wǎng)頁內(nèi)容的實例
- Centos7 Python3下安裝scrapy的詳細步驟
- 淺析python實現(xiàn)scrapy定時執(zhí)行爬蟲
- Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實現(xiàn)代碼
- python3使用scrapy生成csv文件代碼示例
- Python:Scrapy框架中Item Pipeline組件使用詳解
- Python之Scrapy爬蟲框架安裝及簡單使用詳解
相關(guān)文章
Python Flask全棧項目實戰(zhàn)構(gòu)建在線書店流程
這篇文章主要為大家介紹了Python Flask全流程全棧項目實戰(zhàn)之在線書店構(gòu)建實現(xiàn)過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
python+Word2Vec實現(xiàn)中文聊天機器人的示例代碼
本文主要介紹了python+Word2Vec實現(xiàn)中文聊天機器人,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
python利用 pytesseract快速識別提取圖片中的文字((圖片識別)
本文介紹了tesseract的python調(diào)用,也就是pytesseract庫,其中還有一些其他的內(nèi)容并沒有涉及,僅涉及到了圖片提取文字,如果你對其感興趣,可以深入探索一下,也希望能和我探討一下2022-11-11

