使用Scrapy爬取動(dòng)態(tài)數(shù)據(jù)
對(duì)于動(dòng)態(tài)數(shù)據(jù)的爬取,可以選擇selenium和PhantomJS兩種方式,本文選擇的是PhantomJS。
網(wǎng)址:
1.首先第一步,對(duì)中間件的設(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)行請(qǐng)求發(fā)送下載器之前
# 會(huì)先執(zhí)行當(dāng)前的爬蟲中間件 ,在中間件里面使用selenium
# 請(qǐng)求這個(gè)request ,拿到動(dòng)態(tài)網(wǎng)站的數(shù)據(jù) 然后將請(qǐng)求
# 返回給spider爬蟲對(duì)象
if spider.name == 'taobao':
# 使用爬蟲文件的url地址
spider.driver.get(request.url)
for x in range(1 ,12 ,2):
i = float(x) / 11
# scrollTop 從上往下的滑動(dòng)距離
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)
# 這個(gè)地方只能返回response對(duì)象,當(dāng)返回了response對(duì)象,那么可以直接跳過下載中間件,將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í)例化對(duì)象。
item = TaobaospiderItem() item['name'] = title item['price'] = price yield item
在設(shè)置中,打開:
ITEM_PIPELINES = {
'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}
4.第四步,寫入數(shù)據(jù)庫(kù):
進(jìn)入管道文件中。
引入
import sqlite3
寫入數(shù)據(jù)庫(kù)的代碼如下:
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ù)庫(kù)查看數(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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- python使用scrapy發(fā)送post請(qǐng)求的坑
- Python爬蟲框架scrapy實(shí)現(xiàn)downloader_middleware設(shè)置proxy代理功能示例
- Python爬蟲框架scrapy實(shí)現(xiàn)的文件下載功能示例
- python爬蟲框架scrapy實(shí)現(xiàn)模擬登錄操作示例
- Python下使用Scrapy爬取網(wǎng)頁(yè)內(nèi)容的實(shí)例
- Centos7 Python3下安裝scrapy的詳細(xì)步驟
- 淺析python實(shí)現(xiàn)scrapy定時(shí)執(zhí)行爬蟲
- Python使用Scrapy爬蟲框架全站爬取圖片并保存本地的實(shí)現(xiàn)代碼
- python3使用scrapy生成csv文件代碼示例
- Python:Scrapy框架中Item Pipeline組件使用詳解
- Python之Scrapy爬蟲框架安裝及簡(jiǎn)單使用詳解
相關(guān)文章
Python Flask全棧項(xiàng)目實(shí)戰(zhàn)構(gòu)建在線書店流程
這篇文章主要為大家介紹了Python Flask全流程全棧項(xiàng)目實(shí)戰(zhàn)之在線書店構(gòu)建實(shí)現(xiàn)過程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
python+Word2Vec實(shí)現(xiàn)中文聊天機(jī)器人的示例代碼
本文主要介紹了python+Word2Vec實(shí)現(xiàn)中文聊天機(jī)器人,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
用Python徒手?jǐn)]一個(gè)股票回測(cè)框架搭建【推薦】
回測(cè)框架就是提供這樣的一個(gè)平臺(tái)讓交易策略在歷史數(shù)據(jù)中不斷交易,最終生成最終結(jié)果,通過查看結(jié)果的策略收益,年化收益,最大回測(cè)等用以評(píng)估交易策略的可行性。這篇文章主要介紹了用Python徒手?jǐn)]一個(gè)股票回測(cè)框架,需要的朋友可以參考下2019-08-08
Python一行代碼對(duì)話ChatGPT實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了Python一行代碼對(duì)話ChatGPT實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Python的爬蟲框架scrapy用21行代碼寫一個(gè)爬蟲
最近在學(xué)習(xí)Python的爬蟲框架scrapy,通過爬取線報(bào)網(wǎng)站后發(fā)現(xiàn)整個(gè)過程還是挺值得學(xué)習(xí)的,所以下面這篇文章主要就給大家介紹了Python的爬蟲框架scrapy利用21行代碼寫一個(gè)爬蟲的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-04-04
python利用 pytesseract快速識(shí)別提取圖片中的文字((圖片識(shí)別)
本文介紹了tesseract的python調(diào)用,也就是pytesseract庫(kù),其中還有一些其他的內(nèi)容并沒有涉及,僅涉及到了圖片提取文字,如果你對(duì)其感興趣,可以深入探索一下,也希望能和我探討一下2022-11-11

