我正在尝试导航至 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()
最佳答案
你的第一个 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/