硒的Chrome XPath表达式找不到元素

时间:2018-12-03 16:36:32

标签: selenium google-chrome selenium-webdriver xpath

在网页中,我具有以下元素:

....
<select class="widget-listbox form-control" size="6" multiple="multiple">
    <option data-value="sIPSCs%20from%20juvenile%20(P21-30)%20C57BL%2F6J%20male%20mice%20hippocampus%20CA1%20pyramidal%20cell%20(A1)" value="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A1)" class="">sIPSCs&nbsp;from&nbsp;juvenile&nbsp;(P21-30)&nbsp;C57BL/6J&nbsp;male&nbsp;mice&nbsp;hippocampus&nbsp;CA1&nbsp;pyramidal&nbsp;cell&nbsp;(A1)</option>
    <option data-value="sIPSCs%20from%20juvenile%20(P21-30)%20C57BL%2F6J%20male%20mice%20hippocampus%20CA1%20pyramidal%20cell%20(A2)" value="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A2)" class="">sIPSCs&nbsp;from&nbsp;juvenile&nbsp;(P21-30)&nbsp;C57BL/6J&nbsp;male&nbsp;mice&nbsp;hippocampus&nbsp;CA1&nbsp;pyramidal&nbsp;cell&nbsp;(A2)</option>
</select>
....

并且我正在尝试以下xpath表达式来选择第一个options元素(用于硒测试):

//option[contains(text(),"sIPSC")]
//option[text()="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A1)"]
//option[@value="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A1)"]
//select/option[contains(text(),"sIPSC")]
//select/option[text()="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A1)"]
//select/option[@value="sIPSCs from juvenile (P21-30) C57BL/6J male mice hippocampus CA1 pyramidal cell (A1)"]

,但没有显示任何结果(在Chrome,XPath Helper版本2.02;在Chrome版本70.0.3538.110中)。我要查找的元素不在框架内。我还想选择整个字符串“来自幼年(P21-30)C57BL / 6J雄性小鼠海马CA1锥体细胞(A1)的sIPSC”,这可能是一个变量。只是任何字符串。我事先不知道这个字符串的样子...

这次我在做什么错?以上任何一种表达方式都不行吗?

2 个答案:

答案 0 :(得分:2)

要选择第一个选项作为React元素,您需要诱使 WebDriverWait 使元素可点击,并且您可以使用以下任一方法以下( Pythonic )解决方案:

  • XPath 1

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@class='widget-listbox form-control']/option[contains(@data-value,'(A1)')]"))).click()
    
  • XPath 2

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@class='widget-listbox form-control']/option[contains(@value,'(A1)')]"))).click()
    
  • XPath 3

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@class='widget-listbox form-control']/option[contains(.,'(A1)')]"))).click()
    
  • 注意:您必须添加以下导入:

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

答案 1 :(得分:0)

看起来两个选项都包含“ sIPSC”

尝试使用xpath标识元素的唯一性,例如://option[contains(text(),"sIPSC")][contains(text(),"A1")]

如果您总是想要 first (第一)选项: //select/option[contains(text(),"sIPSC")][1]