2017-01-10 10 views
2

私はJavascriptとやりとりできるように、またセレクションが提供する強力なスクレイピングフレームワークを持つために、セレニウムを使ってscrapyを使用しようとしています。私はhttp://www.iens.nlを訪問し、検索バーに "Amsterdam"と入力し、検索ボタンをクリックするスクリプトを書いた。検索ボタンをクリックすると、新しくレンダリングされたページから要素を取り出すためにscrapyが必要になります。残念ながら、scrapyは値を返しません。Selenium + Scrapyの使用

from selenium import webdriver 
from scrapy.loader import ItemLoader 
from scrapy import Request 
from scrapy.crawler import CrawlerProcess 
from properties import PropertiesItem 
import scrapy 


class BasicSpider(scrapy.Spider): 
    name = "basic" 
    allowed_domains = ["web"] 
    # Start on a property page 
    start_urls = ['http://www.iens.nl'] 

    def __init__(self): 
     chrome_path = '/Users/username/Documents/chromedriver' 
     self.driver = webdriver.Chrome(chrome_path) 

    def parse(self, response): 
     self.driver.get(response.url) 
     text_box = self.driver.find_element_by_xpath('//*[@id="searchText"]') 
     submit_button = self.driver.find_element_by_xpath('//*[@id="button_search"]') 
     text_box.send_keys("Amsterdam") 
     submit_button.click() 

     l = ItemLoader(item=PropertiesItem(), response=response) 
     l.add_xpath('description', '//*[@id="results"]/ul/li[1]/div[2]/h3/a/') 

     return l.load_item() 


process = CrawlerProcess() 
process.crawl(BasicSpider) 
process.start() 

"プロパティ" は、このようになります別のスクリプトです:

これは私のコードは次のようになります

from scrapy.item import Item, Field 

class PropertiesItem(Item): 
    # Primary fields 
    description = Field() 

Q:私は正常に要素を見つけるscrapy作るにはどうすればよいですセレンが到達したページのxpathによって「記述」と呼ばれ、出力として返されますか?

ありがとうございます!

+0

あなたのコードは 'parse'に到達していますか? printや何かで – eLRuLL

+0

@eLRuLLそれは 'parse'に達しました。そうでなければ、セレンは次のページに移動しませんでしたか? – titusAdam

+0

ScrapとSeleniumを結合する他の方法として、これを見てみたいかもしれません:http://stackoverflow.com/a/36085533/1204332 –

答えて

3

ItemLoaderに割り当てられているresponseオブジェクトは、scrapyというレスポンスであり、Selenium'sではありません。

私はセレンで返されるページのソースで新しいSelectorを作成することをお勧めします:

from scrapy import Selector 
... 

selenium_response_text = driver.page_source 

new_selector = Selector(text=selenium_response_text) 
l = ItemLoader(item=PropertiesItem(), selector=new_selector) 
... 

その方法をadd_xpathは(あなたが実際に必要としないこと)を代わりにscrapyの応答構造体から情報を取得します。

+0

私が言ったように;私はその速度のためにデータを掻き集めるために掻爬を使いたいと思っています!私はセレンの使い方を知っています。 :) – titusAdam

+0

@titusAdamのスピードは、セレンの中の事実ではありません。スピードが必要な場合は、セレンを完全に削除するか、非同期レンダリングをサポートするものに置き換える必要があります。すなわち、[Splash](http://splash.readthedocs.io/en/stable/) – Granitosaurus

+0

@Granitosaurusは、この例ではセレンのようなスプラッシュを持つページを移動することは可能ですか? – titusAdam