如何通过Selenium和Python使用xpath精确数字

时间:2018-09-29 13:16:30

标签: python selenium selenium-webdriver xpath webdriver

嗨,我正在尝试查找包含文本'01 .0000'的元素,但是在此行之前有一个包含'01 .00'的源代码。如何找到该元素?

源代码:

<div class="gofer-search-results">
<a href="#" class="js-hovered"><span class="name">Communication and Media Studies</span><span class="code">09.01</span></a>
<a href="#" class=""><span class="name">Communication, General</span><span class="code">09.0100</span></a>
<a href="#" class=""><span class="name">Speech Communication and Rhetoric</span><span class="code">09.0101</span></a>
<a href="#" class=""><span class="name">Mass Communication/Media Studies</span><span class="code">09.0102</span></a>
<a href="#" class=""><span class="name">Communication and Media Studies, Other</span><span class="code">09.0199</span></a>
<a href="#" class=""><span class="name">Animal Sciences</span><span class="code">01.09</span></a></div>

这是我尝试的代码:

driver.find_element_by_xpath("//span/div/a/span[text()= 01.0000]")
driver.find_element_by_xpath("//span/div/a/span[normalize-space()= 01.0000]")
driver.find_element_by_xpath("//span/div/a/span[./text()= 01.0000]")

我一直得到01.00元素而不是01.0000元素。

1 个答案:

答案 0 :(得分:1)

要找到文本为 01.0000 的元素,可以使用以下任一解决方案:

  • 使用 text()

    driver.find_element_by_xpath("//span/div/a/span[text()='01.0000']")
    
  • 使用 normalize-space()

    driver.find_element_by_xpath("//span/div/a/span[normalize-space()='01.0000']")