Python+Selenium xpath位置決め同じ要素に遭遇した場合の解決方法親ノードサブノードの検索


1、#親ノードにナビゲートしてから、親ノードから指定したノードを探します.
例:直接使用できないことに注意
driver.find_element_by_xpath('//*[@id="branch_inquiry"]').find_element_by_class_name('city-picker-span')

使用法
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

driver = webdriver.Chrome()
driver.get("http://intl.sit.sf-express.com:8980/")
from selenium.webdriver import ActionChains
import time
driver.find_element_by_xpath('/html/body/div[3]/div[2]/a[5]').click()
time.sleep(1)
service_coverage = driver.find_element_by_xpath('//*[@id="range_inquiry"]').find_element_by_class_name('city-picker-span')
print(service_coverage.text)
service_coverage.click()

2、同一レベルでないxpath位置決め方法
     
driver.find_element_by_xpath("//input[@id='cityAddress1']/following-sibling::span").click()
3、         
# 1.    
print driver.find_element_by_id('B').find_element_by_tag_name('div').text

# 2.xpath      
print driver.find_element_by_xpath("//div[@id='B']/div").text

# 3.css selector      
print driver.find_element_by_css_selector('div#B>div').text

# 4.css selector nth-child
print driver.find_element_by_css_selector('div#B div:nth-child(1)').text

# 5.css selector nth-of-type
print driver.find_element_by_css_selector('div#B div:nth-of-type(1)').text

# 6.xpath  child
print driver.find_element_by_xpath("//div[@id='B']/child::div").text
4、

# 1.xpath: `.`      ; '..'     
print driver.find_element_by_xpath("//div[@id='C']/../..").text
# 2.xpath  parent
print driver.find_element_by_xpath("//div[@id='C']/parent::*/parent::div").text

5、 ノードから ノードを する
# 1.xpath,            
print driver.find_element_by_xpath("//div[@id='D']/../div[1]").text
# 2.xpath  preceding-sibling
print driver.find_element_by_xpath("//div[@id='D']/preceding-sibling::div[1]").text

6、 ノードから ノードを する
# 1.xpath,            
print driver.find_element_by_xpath("//div[@id='D']/../div[3]").text
# 2.xpath  following-sibling
print driver.find_element_by_xpath("//div[@id='D']/following-sibling::div[1]").text
# 3.xpath  following
print driver.find_element_by_xpath("//div[@id='D']/following::*").text
# 4.css selector +
print driver.find_element_by_css_selector('div#D + div').text
# 5.css selector ~
print driver.find_element_by_css_selector('div#D ~ div').text

7、その のXapth め
     :         (            )
By.xpath("html/body/div/form/input")
By.xpath("//input")
     :        
By.xpath("//input[4]")
     :  xpath    (   2、 3       )
By.xpath("//input[@id='kw1']")
By.xpath("//input[@type='name' and @name='kw1']")
     :         (      )
By.xpath("//input[start-with(@id,'nice')
By.xpath("//input[ends-with(@id,'   ')
By.xpath("//input[contains(@id,'   ')]")