将Xpath元素的文本放入数组

时间:2013-11-18 17:22:27

标签: ruby arrays xpath selenium selenium-webdriver

我正在尝试使用Selenium。问题如下:

文档结构:

<div class="jsSkills oSkills">
 <a class="oTag oTagSmall oSkill" href="/contractors/skill/software-testing/" data-contractor="749244">software-testing</a>
 <a class="oTag oTagSmall oSkill" href="/contractors/skill/software-qa-testing/" data-contractor="749244">software-qa-testing</a>
 <a class="oTag oTagSmall oSkill" href="/contractors/skill/blog-writing/" data-contractor="749244">blog-writing</a>
</div>

我需要获取所有a的文本,如下所示:

{"software-testing", "software-qa-testing", "blog-writing"}

我试过了:

contrSkill = driver.find_element(:xpath, "//div[contains(@class, 'jsSkills')]").text
puts contrSkill

但得到了这个:

"software-testingsoftware-qa-testingblog-writing"

请解释如何正确制作阵列。

1 个答案:

答案 0 :(得分:1)

您应该获得所需的所有链接元素(使用find_elements)。然后你可以迭代每个链接并将其文本收集到一个数组中(Ruby有一个collect方法可以帮助解决这个问题。)

# Get all of the link elements within the div
skill_links = driver.find_elements(:xpath, "//div[contains(@class, 'jsSkills')]/a")

# Create an array of the text of each link
skill_text_array = skill_links.collect(&:text)
p skill_text_array
#=> ["software-testing", "software-qa-testing", "blog-writing"]