[英]How can I find visible only elements on a page with Selenium Webdriver?
[英]How can I perform an action based on the contents of a div with Selenium Webdriver?
我有一個使用Selenium Webdriver和Nokogiri的Ruby應用程序。 我想選擇一個類,然后針對對應於該類的每個div,我要根據div的內容執行操作。
例如,我正在解析以下頁面:
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies
這是一個搜索結果頁面,我正在尋找描述中帶有“采用”字樣的第一個結果。 因此,該漫游器應查找className: "result"
div,每檢查一個.description
div是否包含單詞“ adoption”,如果包含,請單擊.link
div。 換句話說,如果.description
不包含該單詞,則該漫游器會.result
到下一個.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
您可以使用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
處理每個迭代的模式將取決於對每個項目執行的操作類型。 如果操作是單擊,那么您將無法列出所有要單擊的鏈接,因為第一次單擊將加載新頁面,從而使元素列表過時。 因此,如果您希望單擊每個鏈接,那么一種方法是使用一個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!"
我沒有用ruby編寫代碼,但是可以在python中實現的一種方法是:
driver.find_elements
注意元素是如何復數的,我將抓住所有鏈接並將它們放入一個數組中。
href = driver.find_elements_by_xpath("//div[@class='rc]/h3/a").getAttribute("href");
然后以相同的方式獲取所有描述。 如果描述中包含單詞“ Adoption”,請對描述的每個元素進行for循環。
例如:
如果description [6]包含采用一詞,則找到字符串href [6]並導航至href [6]。
我希望這是有道理的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.