python - XPath 定位 sibling 之后的 child

标签 python selenium xpath selenium-webdriver

我正在将Selenium 用于Python 2.7.10

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

<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 特别感兴趣。这是因为上面的函数在网络代码中使用 “ETF Home Page:” 作为要搜索的内容的标识符。

最佳答案

你几乎是正确的:

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

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

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

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")

关于python - XPath 定位 sibling 之后的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31835893/

相关文章:

xpath - XSLT 1.0 转换可以用作纯 XPath 1.0 位置路径评估器吗?

python - 如何在多处理函数中使用 wxPython 启用/禁用按钮?

python - 将两个路径与公共(public)文件夹组合

node.js - 如何使用 Cypress 测试登录 GSuite 日历

python - 如何创建 python selenium 应用程序及其驱动程序?

python - Selenium 在 PC 和 RPI 上的性能差异

XPATH 选择包含一些字符串但不包含其他字符串

python - Celery 守护进程的多个队列

python - matplotlib 绘图几乎没有错误

python - 难以将不同页面的项目打印在一起