跨度文本未返回硒唯一元素

时间:2018-11-13 22:02:59

标签: python selenium xpath css-selectors webdriverwait

在网页上,此元素是唯一包含确切文字“ Volgende stap”的元素:

<span class="b-button--label ng-binding ng-scope" ng-if="arrowDirection === 'right'">Volgende stap</span>

但是当我尝试使用xpath选择包含这些单词的元素(列表)时:

driver.find_elements_by_xpath("//span[contains(text(),'Volgende')]")
driver.find_elements_by_xpath("//span[.='Volgende stap']")
driver.find_elements_by_xpath("//span[text()='Volgende stap']")

我不断收到一个空列表(如果是element not found而不是find_element,则为find_elements

这是通往我正在处理的html页面的脚本:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait

driver = webdriver.Chrome()
driver.get("https://www.greetz.nl/kaarten/verjaardag/man")
wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='/kaart/detail/greetz-verjaardagskaart---abracadabra/1142778148']"))).click()
wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Kaart bewerken']"))).click()

2 个答案:

答案 0 :(得分:2)

它位于iframe中。首先切换到它,然后尝试通过文本查找:

frame = driver.find_element_by_css_selector('frame.personalize--frame')
driver.switch_to.frame(frame)

答案 1 :(得分:1)

根据HTML,所需元素的文字为 Volgende stap ({Volgende stap )在<iframe>之内,因此您必须:

  • 诱导 WebDriverWait 以使所需的框架可用并切换到它。
  • 诱导 WebDriverWait 以使所需的元素可点击
  • 您可以使用以下解决方案:

    • 使用CSS_SELECTOR

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.personalize--frame[src='//www.greetz.nl/editor/desktop.html']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.b-button--label.ng-binding.ng-scope[ng-if*='right'][]"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='personalize--frame' and @src='//www.greetz.nl/editor/desktop.html']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='b-button--label ng-binding ng-scope' and contains(text(),'Volgende')]"))).click()
      

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

在这里您可以找到有关Ways to deal with #document under iframe的相关讨论