如果显示元素,则查找元素的选择器无效

时间:2017-09-09 05:59:48

标签: python python-3.x selenium xpath selenium-webdriver

我正试图导航到Centrebet,如果体育下不存在导航菜单,那么我想点击体育。我有以下代码虽然它一直给出无效的选择器。

element = driver.find_element_by_xpath("//ul[id*='accordionMenu1_ulSports'][style*='display: none;']")
if element.is_displayed():
    element = driver.find_element_by_xpath(".//a[@class ='head-style3'][contains(text(), 'Sports')]").click()

我也尝试过使用

element = driver.find_element_by_xpath(".//*[@id = 'accordionMenu1_ulSports'][contains(text(), 'Soccer')]")
if element.is_not_displayed():
    element = driver.find_element_by_xpath(".//a[@class ='head-style3'][contains(text(), 'Sports')]").click()

它一直给无效的选择器任何想法?感谢enter image description here

1 个答案:

答案 0 :(得分:1)

你的第一个XPath

"//ul[id*='accordionMenu1_ulSports'][style*='display: none;']"

是XPath和CSS选择器的混合体。纯XPath应该看起来像

"//ul[contains(@id, 'accordionMenu1_ulSports') and contains(@style, 'display: none;')]"

你的第二个XPath

".//*[@id = 'accordionMenu1_ulSports'][contains(text(), 'Soccer')]

与所需的ul不匹配,因为它没有文字节点"Soccer" - 它的兄弟链接的文字内容......

尝试

//ul[@id='accordionMenu1_ulSports' and ./preceding-sibling::a[.='Soccer']]

此外,webElement没有is_not_displayed()这样的属性。我想你应该试试not element.is_displayed()

完整代码应该是

element = driver.find_element_by_xpath("//ul[@id='accordionMenu1_ulSports' and ./preceding-sibling::a[.='Soccer']]")
if not element.is_displayed():
    element = driver.find_element_by_xpath(".//a[@class ='head-style3'][contains(text(), 'Sports')]")
    element.click()

更新

要知道"Soccer"元素是否可访问,您只需检查"display"的{​​{1}}样式值:

"Sports"