我正在将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/