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

标签 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

最佳答案

你的第一个 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() 这样的属性。我猜你应该尝试 而不是 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" 元素是否可访问,您可以检查 "Sports""display" 样式值:

sports = driver.find_element_by_id("accordionMenu1_ulSports")
if sports.get_attribute("style") == "display: none;":
    driver.find_element_by_xpath('//ul[@id="menu_acc"]/li[3]/a').click()

soccer = driver.find_element_by_link_text("SOCCER")

关于python - 如果显示元素,则查找元素的选择器无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46127629/

相关文章:

python - 将十进制整数转换为小端字符串 ('\x##\x##...' )

Python 如何读取匿名 linux 文件的 GPIO 事件

java - Tomcat使用selenium时无法编译类

java - 如何在selenium java中识别 'mat-calendar-body-cell'?

python - Tensorflow 序列扩展的动态 __len__?

python - 如何根据日期索引连接一系列数据以形成 df 而不会丢失数据

python - dd 命令权限被拒绝 Python

Python3 - 而 ids > 停止 : TypeError: unorderable types: str()> int()

python - tensorflow 预测序列

html - 我需要 CSS 选择器来选择包含给定文本的元素