Joe*_*ano 5 ruby selenium bots webdriver 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
Run Code Online (Sandbox Code Playgroud)
这是一个搜索结果页面,我正在寻找描述中带有"Adoption"一词的第一个结果.所以机器人应该寻找div className: "result",每一个检查它的.descriptiondiv是否包含单词"adoption",如果是,请点击.linkdiv.换句话说,如果.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
Run Code Online (Sandbox Code Playgroud)
您可以使用contains()获取XPath包含"采用"和"采用"的元素列表,然后使用union运算符(|)来结合"采用"和"采用"的结果.见下面的代码:
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
Run Code Online (Sandbox Code Playgroud)
我不使用 ruby 编写代码,但可以使用 python 编写代码的一种方法是:
driver.find_elements
Run Code Online (Sandbox Code Playgroud)
注意 elements 是复数的,我会抓取所有链接并将它们放入一个数组中,例如。
href = driver.find_elements_by_xpath("//div[@class='rc]/h3/a").getAttribute("href");
Run Code Online (Sandbox Code Playgroud)
然后以同样的方式获取所有描述。如果描述中包含“采用”一词,则对描述的每个元素执行 for 循环,导航到该网站。
例如:
如果描述 [6] 包含“采用”一词,则找到字符串 href[6] 并导航到 href[6]。
我希望这是有道理的!