2016-03-03 39 views
5

我有一個使用Selenium Webdriver和Nokogiri的Ruby應用程序。我想選擇一個類,然後爲每個對應於該類的div,我想根據div的內容執行操作。如何根據Selenium Webdriver的div內容執行操作?

例如,我解析如下頁面:

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies 

這是搜索結果的頁面,我期待與描述中的「收養」這個詞的第一個結果。所以機器人應該尋找與className: "result" div,爲每一個檢查它的.description div是否包含單詞「收養」,如果是這樣,點擊.link股利。換句話說,如果.description不包含那個單詞,那麼機器人會移動到下一個.result

這是我到目前爲止,剛剛點擊的第一個結果:

require "selenium-webdriver" 
require "nokogiri" 
driver = Selenium::WebDriver.for :chrome 
driver.navigate.to "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies" 
driver.find_element(:class, "link").click 

回答

1

我不Ruby代碼,但你可以做到這一點在Python的一種方法是:

driver.find_elements 

注意元素是如何複數的,我會抓住所有的鏈接並把它們放到一個數組中。

href = driver.find_elements_by_xpath("//div[@class='rc]/h3/a").getAttribute("href"); 

然後以相同的方式獲取所有描述。如果描述中的「Adoption」字樣導航到該網站,則對每個描述元素執行for循環。

例如:

如果描述[6]已經字通過找到字符串HREF [6],並導航到HREF [6]。

我希望有道理!

6

您可以使用contains()獲取XPath包含「採用」和「採用」的元素列表,然後使用聯合運算符(|)合併「採用」和「採用」結果。請參閱下面的代碼:

driver = Selenium::WebDriver.for :chrome 
driver.navigate.to "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies" 
sleep 5 
items = driver.find_elements(:xpath,"//div[@class='g']/div[contains(.,'Adopt')]/h3/a|//div[@class='g']/div[contains(.,'adopt')]/h3/a") 
for element in items 
    linkText = element.text 
    print linkText 
    element.click 
end 
2

處理每個迭代的模式將取決於每個項目上執行的操作的類型。如果該操作是點擊操作,則無法列出所有鏈接以點擊每個鏈接,因爲第一次點擊會加載新頁面,從而使元素列表過時。 所以,如果你想點擊每一個環節上,再一個辦法是使用XPath包含鏈接的位置,每次迭代:

# iteration 1 
driver.find_element(:xpath, "(//h3[@class='r']/a)[1]").click # click first link 

# iteration 2 
driver.find_element(:xpath, "(//h3[@class='r']/a)[2]").click # click second link 

下面是從結果頁面的每個鏈接的點擊一個例子:

require 'selenium-webdriver' 

driver = Selenium::WebDriver.for :chrome 
wait = Selenium::WebDriver::Wait.new(timeout: 10000) 

driver.navigate.to "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies" 

# define the xpath 
search_word = "Puppies" 
xpath = ("(//h3[@class='r']/a[contains(.,'%s')]" % search_word) + ")[%s]" 

# iterate each result by inserting the position in the XPath 
i = 0 
while true do 

    # wait for the results to be loaded 
    wait.until {driver.find_elements(:xpath, "(//h3[@class='r']/a)[1]").any?} 

    # get the next link 
    link = driver.find_elements(:xpath, xpath % [i+=1]).first 
    break if !link 

    # click the link 
    link.click 

    # wait for a new page 
    wait.until {driver.find_elements(:xpath, "(//h3[@class='r']/a)[1]").empty?} 

    # handle the new page 
    puts "Page #{i}: " + driver.title 

    # return to the main page 
    driver.navigate.back 
end 

puts "The end!" 
相關問題