使用Scrapy爬取動態(tài)數(shù)據(jù)
對于動態(tài)數(shù)據(jù)的爬取,可以選擇selenium和PhantomJS兩種方式,本文選擇的是PhantomJS。
網(wǎng)址:
1.首先第一步,對中間件的設(shè)置。
進(jìn)入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進(jìn)行請求發(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進(jìn)行解析
return response
在設(shè)置中,要將middlewares設(shè)置打開。
進(jìn)入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)建實(shí)例化對象。
item = TaobaospiderItem() item['name'] = title item['price'] = price yield item
在設(shè)置中,打開:
ITEM_PIPELINES = {
'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}
4.第四步,寫入數(shù)據(jù)庫:
進(jìn)入管道文件中。
引入
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,
}
因?yàn)樵谏弦徊?,我們已?jīng)將管道傳送設(shè)置打開,所以這一步可以不用重復(fù)操作。
然后運(yùn)行程序,打開數(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實(shí)現(xiàn)downloader_middleware設(shè)置proxy代理功能示例
- Python爬蟲框架scrapy實(shí)現(xiàn)的文件下載功能示例
- python爬蟲框架scrapy實(shí)現(xiàn)模擬登錄操作示例
- Python下使用Scrapy爬取網(wǎng)頁內(nèi)容的實(shí)例
- Centos7 Python3下安裝scrapy的詳細(xì)步驟
- 淺析python實(shí)現(xiàn)scrapy定時執(zhí)行爬蟲
- Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼
- python3使用scrapy生成csv文件代碼示例
- Python:Scrapy框架中Item Pipeline組件使用詳解
- Python之Scrapy爬蟲框架安裝及簡單使用詳解
相關(guān)文章
詳解Python設(shè)計(jì)模式編程中觀察者模式與策略模式的運(yùn)用
這篇文章主要介紹了Python設(shè)計(jì)模式編程中觀察者模式與策略模式的運(yùn)用,觀察者模式和策略模式都可以歸類為結(jié)構(gòu)型的設(shè)計(jì)模式,需要的朋友可以參考下2016-03-03
Python functools模塊學(xué)習(xí)總結(jié)
這篇文章主要介紹了Python functools模塊學(xué)習(xí)總結(jié),本文講解了functools.partial、functool.update_wrapper、functool.wraps、functools.reduce、functools.cmp_to_key、functools.total_ordering等方法的使用實(shí)例,需要的朋友可以參考下2015-05-05
Python使用OpenCV實(shí)現(xiàn)虛擬縮放效果
OpenCV?徹底改變了整個圖像處理領(lǐng)域。從圖像分類到對象檢測,我們不僅可以使用?OpenCV?庫做一些很酷的事情,而且還可以構(gòu)建一流的應(yīng)用程序。本文將用OpenCV實(shí)現(xiàn)虛擬縮放,需要的可以參考一下2022-02-02
用Python刪除本地目錄下某一時間點(diǎn)之前創(chuàng)建的所有文件的實(shí)例
下面小編就為大家分享一篇用Python刪除本地目錄下某一時間點(diǎn)之前創(chuàng)建的所有文件的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
Django實(shí)現(xiàn)微信小程序的登錄驗(yàn)證功能并維護(hù)登錄態(tài)
這篇文章主要介紹了Django實(shí)現(xiàn)小程序的登錄驗(yàn)證功能并維護(hù)登錄態(tài),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Django Rest Framework構(gòu)建API的實(shí)現(xiàn)示例
本文主要介紹了Django Rest Framework構(gòu)建API的實(shí)現(xiàn)示例,包含環(huán)境設(shè)置、數(shù)據(jù)序列化、視圖與路由配置、安全性和權(quán)限設(shè)置、以及測試和文檔生成這幾個步驟,具有一定的參考價值,感興趣的可以了解一下2024-08-08
From CSV to SQLite3 by python 導(dǎo)入csv到sqlite實(shí)例
今天小編就為大家分享一篇From CSV to SQLite3 by python 導(dǎo)入csv到sqlite實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python數(shù)據(jù)分析之聚類分析(cluster analysis)
聚類分析本身不是一個特定的算法,而是要解決的一般任務(wù)。它可以通過各種算法來實(shí)現(xiàn),這些算法在理解群集的構(gòu)成以及如何有效地找到它們方面存在顯著差異。這篇文章主要介紹了python數(shù)據(jù)分析之聚類分析(cluster analysis),需要的朋友可以參考下2021-11-11

