3

I am using Selenium for Python 2.7.10.

With XPath, I would like to locate the link in a href, following the sibling to minimal-list__title (i.e. I'm looking for the child beneath minimal-list__value). Which XPath should I use?

<span class="minimal-list__title">ETF Home Page:</span>
<span class="minimal-list__value">
    <a href="http://www.robostoxetfs.com/">ROBO</a>

This is the current attempt:

from selenium import webdriver as driver
from selenium.common.exceptions import NoSuchElementException

def get_link(driver, key):
    key = key + ":"
    try:
        find_value = driver.find_element_by_xpath("//span[@class='minimal-list__title' and . = '%s']/following-sibling::span/*[1]::a" % key).text
    except NoSuchElementException:
        return None
    else:
        value = re.search(r"(.+)", find_value).group().encode("utf-8")
        return value

website = get_link(driver, "ETF Home Page")
print "Website: %s" % website

Note that I am specifically interested in a XPath that gets the link from the child of the following sibling. This is because the function above uses "ETF Home Page:" in the web code as an identifier for what to search for.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
P A N
  • 5,642
  • 15
  • 52
  • 103

3 Answers3

2

You're almost correct:

//span[@class = "minimal-list__title" and . = "ETF Home Page:"]/following-sibling::span/a

Note that you don't need to worry about multiple elements matching the locator since you are using find_element_by_xpath() and it would give you the first matching element.

Though, if it would makes sense in your case and you know the "ROBO" label beforehand:

driver.find_element_by_link_text("ROBO")

To get an attribute value, use get_attribute():

find_value = driver.find_element_by_xpath('//span[@class = "minimal-list__title" and . = "ETF Home Page:"]/following-sibling::span/a').get_attribute("href")
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks :) This gives me the element text `ROBO`, but I would like to get the url in `href`. Something like `/following-sibling::span/a[@href]`? Produces the same result however. – P A N Aug 05 '15 at 15:10
0
String e = driver.findElement(By.xpath("//*[contains(@class,"minimal-list__value")]/a)).getAttribute("href");

//*[contains(@class,"minimal-list__value")]/a is the xpath, the getAttribute will give you the desired result.

MarmiK
  • 5,639
  • 6
  • 40
  • 49
0

Based on the text ETF Home Page: to extract the link http://www.robostoxetfs.com/ from the child node of the following sibling you can use either of the following based Locator Strategies:

  • Using xpath and following-sibling:

    print(driver.find_element_by_xpath("//span[text()='ETF Home Page:']//following-sibling::span/a").get_attribute("href"))
    
  • Using xpath and following:

    print(driver.find_element_by_xpath("//span[text()='ETF Home Page:']//following::span/a").get_attribute("href"))
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352