XPath 在兄弟姐妹之后定位孩子 [英] XPath locate child following sibling

查看:27
本文介绍了XPath 在兄弟姐妹之后定位孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Selenium 用于 Python 2.7.10.

使用 XPath,我想在 a href 中找到链接,跟随 minimal-list__title 的兄弟(即我是在 minimal-list__value 下寻找孩子).我应该使用哪个 XPath?

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>

这是当前的尝试:

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

请注意,我对 XPath 尤其感兴趣,该 XPath 从以下兄弟的子节点获取链接.这是因为上述函数在 Web 代码中使用 "ETF Home Page:" 作为搜索内容的标识符.

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.

推荐答案

你几乎是对的:

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

请注意,您无需担心与定位器匹配的多个元素,因为您使用的是 find_element_by_xpath(),它会给您第一个匹配元素.

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.

不过,如果这对您的情况有意义并且您事先知道ROBO"标签:

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

driver.find_element_by_link_text("ROBO")

<小时>

要获取属性值,请使用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")

这篇关于XPath 在兄弟姐妹之后定位孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆