2017-07-06 8 views
0

最近、私はscrapyを使用し始めています。ページをクロールすると、表示されている通貨の問題が発生しています。 Change currency特定の解析でjavascriptスクリプトを実行する

は、私は同じことを行うことができますが、JavaScriptの次のスクリプトを使用して::これは私が実際の通貨を変更する]をクリックする必要があるページの一部である setCurrency(1) 、私はこれをしなければなりませんすべてのページで、すべての商品が同じ通貨を使用していることを確認してください。私が読んだことから、私はこれを行うためにスプラッシュを使用することができますが、私が間違っている場合は私を修正しますが、コードはスパイダーのコンストラクタで1回だけ実行されます。 これは、製品を抽出する解析でのみ実行する方法はありますか。私のコードは次のようである:

def parse(self, response): 
    rutas = response.xpath("//a[@class='nonblock nontext rounded-corners rgba-background clip_frame grpelem']/@href").extract() 
    for ruta in rutas: 
     ruta_abs = response.urljoin(ruta) 
     yield scrapy.Request(url=ruta_abs, callback=self.parse_producto) 

def parse_producto(self, response): 
    #Se debe ejecutar antes un script para cambiar la divisa 
    nombre = response.xpath("//h1/text()").extract_first() 
    #También conocido como "Referencia" por la página: 
    codigo = response.xpath("//p[@id='product_reference']/span/text()").extract_first() 
    descripcion = response.xpath("//div[@id='short_description_block']/div/p/text()").extract_first() 
    url_foto = response.xpath("//div[@id='image-block']/span/img/@src").extract_first() 
    precio = '.'.join(response.xpath("//span[@id='our_price_display']/text()").re(r"\d+")) 
    categorias = response.xpath("//span[@class='navigation_page']/span/a/span/text()").extract() 
    categoria_actual = '' 
    num_categorias = len(categorias) 
    if num_categorias > 1: 
     num_categorias = (num_categorias-1)*-1 
     categoria_actual = categorias[num_categorias] 
    url_producto = response.url 
    caract = response.xpath("//section[@class='page-product-box']/table[@class='table-data-sheet']/tr/td/text()").extract() 
    ficha_tecnica = [] 
    if len(caract) > 1: 
     ficha_tecnica = list(zip(caract[0::2],caract[1::2])) 
    #Genero objeto producto: 
    producto = Producto_tienda() 
    producto['nombre'] = nombre 
    producto['descripcion'] = descripcion 
    producto['url_foto'] = url_foto 
    producto['precio'] = precio 
    producto['id_tienda'] = 2 
    producto['tienda'] = 'ARTEC' 
    producto['url_producto'] = url_producto 
    producto['codigo'] = codigo 
    producto['categoria'] = categoria_actual 
    producto['ficha_tecnica'] = ficha_tecnica 
    yield producto 

は、私はあなたが法的な問題を避けるために名前、許可されているドメインとstart_urlsを設定するコードのbegginingをommited。

スパイダーがparse_producto関数をクロールするたびにjavascriptコードを実行する必要があります。それを行う方法はありますか?より多くの情報が必要な場合は、私はあなたにそれを与えることができます。

ありがとうございます!

答えて

0

セレン+ phantomJSとDownloaderミディウェアを使用できます ここにはgoogleのクロール用に書いたquick crawlerのスニペットがあります。ドライバpage_sourceを使ってHtmlResponseを返す前に、ここで(通貨ボタンをクリックするなどして)行う必要があるすべてを行うことができます。

# -*- coding: utf-8 -*- 
from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from scrapy.http import HtmlResponse 
from scrapy.exceptions import IgnoreRequest 
import time 


class SeleniumMiddleware(object): 
    def __init__(self): 
     self.driver = webdriver.PhantomJS() 

    def process_request(self, request, spider): 
     self.driver.get(request.url) 
     try: 
      WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "r"))) 
      body = self.driver.page_source 
      return HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=request) 
     except Exception as e: 
      # Timeout on WebDriverWait 
      raise IgnoreRequest 

あなたはまた、例えば、settings.pyにDownloaderMiddlewareを設定する必要があります。

DOWNLOADER_MIDDLEWARES = { 
    'selenium_downloader_middleware.middlewares.SeleniumMiddleware': 723, 
} 
関連する問題