Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium > Web Drive : how to find a nested element by xpath (ruby)

I have a nested <div>:

<div id="international-map">
 <div id='a'>
    <a> link a1 </a>
    <a> link a2 </a>
    <a> link a3 </a>
  </div>
  <div id='b'>
       <a> link b1 </a>
       <a> link b2 </a>
  </div>
</div>

How can I get all the links under 'international-map'?

I tried two approaches and failed :(

  1. div= @driver.find_element(:id => 'international-map')
  2. [email protected]_elements(:xpath => "//div[@id='international-map']//div[@tag_name='a']")

thank you (even a C# and Java code helps)

like image 919
BehranG BinA Avatar asked Jun 12 '13 14:06

BehranG BinA


People also ask

How do I find the web element using XPath?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

How do I find the XPath of a div?

We can find an element using the xpath locator with Selenium webdriver. To identify the element with xpath, the expression should be //tagname[@attribute='value']. To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute.

Can XPath locate element using text?

The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes.

How use contains in XPath Selenium?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]


2 Answers

Okay! You can also use #css or #xpath as below:

@driver.find_elements(:css,"div#international-map a").map(&:text)
# => [" link a1 ", " link a2 ", " link a3 ", " link b1 ", " link b2 "]

or

@driver.find_elements(:xpath,"//div[@id = 'international-map']//a").map(&:text)
# => [" link a1 ", " link a2 ", " link a3 ", " link b1 ", " link b2 "]
like image 119
Arup Rakshit Avatar answered Dec 31 '22 09:12

Arup Rakshit


The correct XPath expression is

//div[@id = 'international-map']//a/string()
like image 23
dirkk Avatar answered Dec 31 '22 10:12

dirkk