2017-09-14 67 views
-1

我試圖抓取一個網站(恭敬地)。我嘗試過使用Nokogiri,然後進行機械化,然後因爲我正在抓取的網站正在動態加載表單,所以我不得不使用webdriver。我目前使用ruby的watir。ruby​​ watir - 從搜索中獲取所有div的內部內容

什麼,我試圖做的,是要填寫動態表單與select,點擊提交,將頁面的結果部分(形式呈現同一頁面上的結果),並收集所有的div信息(遍歷子div尋找hrefs)。

def scrape 
    browser = Watir::Browser.new 

    browser.goto 'http://www.website-link.com' 

    browser.select_list(:id => 'city').select('cityName') 

    browser.link(:id, 'btnSearch').click 

    # this part; results from search are in this div w/ this ID 
    # however, iterating through this list does not work the way i expected 
    browser.div(:id, 'resultsDiv').divs.each do |div| 
     p div 
    end 

    browser.close 
    end 

現在這個返回

#<Watir::Div: located: true; {:id=>"resultsDiv", :tag_name=>"div"} --> {:tag_name=>"div", :index=>0}> 
#<Watir::Div: located: true; {:id=>"resultsDiv", :tag_name=>"div"} --> {:tag_name=>"div", :index=>1}> 
#<Watir::Div: located: true; {:id=>"resultsDiv", :tag_name=>"div"} --> {:tag_name=>"div", :index=>2}> 

其查看頁面源看起來像有在resultsDiv內3周的div這也許正是那些索引。我想我是什麼期待(來自Nokogiri/Mechanize)是一個操縱對象。

有沒有人有這樣的經驗,可以指向正確的方向嗎?

+1

那些是對象。索引被分配給從集合創建的元素的選擇器實例變量,以便在它們過期時重新定位它們。 'p div.text'或'p div.inner_html'你在找什麼?另外,我只是寫了watigiri寶石,它結合了nokogiri的等待,如果你想嘗試一下,我會很樂意提供反饋意見。 https://github.com/titusfortner/watigiri – titusfortner

+0

@titusfortner以及'resultsDiv'是一個父div,它擁有我正在尋找的信息,但要獲得它需要更多的遍歷。我主要尋找的是如果這些物體能夠訪問他們的子元素。 –

+1

如果您可以編輯您的問題以在搜索輸出中包含一些示例HTML,並指出您嘗試獲取的信息,那麼這對幫助您的人將大有幫助。 –

回答

0

如果已知所需的順序,可以這樣做:
browser.driver.find_elements(:ID => 'resultsDiv')[n]的。點擊
或 browser.div(:ID => 'resultsDiv')[n]的。點擊
或 browser.div(:ID, 'resultsDiv')DIV(:ID, 'id_n')點擊

+0

爲什麼在使用Id時在元素()的位置使用div()?如果它是id,它不會與xpath形成硒等價物,它只是使用帶selenium代碼的id定位符。所以使用div()在這個地方是沒用的。 – RAJ

+1

你可以在任何元素中使用id,div可以有相同的id,你可以使用元素或div,這是你的選擇,這就是爲什麼我使用不同的方式來做同樣的事情。 – user8609295

+0

我知道id可以與元素或div一起使用。但使用div不會對元素有任何幫助。但是,當你使用div(text:'something')over element(text:'something')將會有利於你。它將不同的xpath映射到selenium driver.find_element()。 – RAJ