如何使用 Python Selenium webdriver 获取 li 内的跨度值?

How to get the value of a span inside a li using Python Selenium webdriver?

我正在尝试从我的 HTML 页面获取 SCN 的值,该页面采用这种格式 -

<html>
    <body>
        <div class="hs-customerdata hs-customerdata-pvalues">
            <ul>
                <li class="hs-attribute">
                    <map-hs-label-value map-hs-lv-label="ACCOUNTINFO.SCN" map-hs-lv-value="89862530">
                    <span class="hs-attribute-label" hs-context-data="" translate="" hs-channel="abcd" hs-device="desktop">SCN:</span>
                    <span ng-bind-html="value | noValue | translate : params" class="hs-attribute-value" context-data="" map-v-key="89862530" map-v-params="" hs-channel="abcd" hs-device="desktop">
                    89862530</span>
                    </map-hs-label-value>
                </li>
            </ul>
        </div>
    </body>
</html>

截至目前,我尝试了不同的方法,但无法达到跨度并获取 SCN 值。

我试过了-

scn = self.driver.find_elements_by_xpath(".//span[@class = 'hs-attribute-value']") 

这给出了 ElementNotFound 错误。我最接近的是 -

div_element = self.driver.find_element_by_xpath('//div[@class="hs-customerdata hs-customerdata-personal"]/ul/li[@class="hs-attribute"]')

然后当我做 -

print(div_element.get_attribute('innerHTML')) 

我得到 -

<map-hs-label-value map-hs-lv-label="ACCOUNTINFO.SCN" map-hs-lv-value="{{::customerData.details.scn}}"></map-hs-label-value>

但我无法超越这一点。我是使用 Webdriver 的新手,无法弄清楚这一点。任何帮助将不胜感激。

  1. 您可以将带有文本 SCN:span 元素定位为 //span[text()='SCN:']
  2. 文本为 89862530 的元素将是点 1
  3. 中元素的 following-sibling
  4. 把所有东西放在一起:

    driver.find_element_by_xpath("//span[text()='SCN:']/following-sibling::span").text
    

    演示:

参考文献:

SCN 的值,即 89862530 反映在 3 个不同的地方,您可以从任何一个地方提取它,从而导致 WebDriverWait 用于 visibility_of_element_located() 并且您可以使用以下任一项 :

  • <map-hs-label-value> 标签 map-hs-lv-value 属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located()((By.XPATH, "//div[@class='hs-customerdata hs-customerdata-pvalues']/ul/li/map-hs-label-value"))).get_attribute("map-hs-lv-value"))
    
  • <span> 标签 map-v-key 属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located()((By.XPATH, "//div[@class='hs-customerdata hs-customerdata-pvalues']/ul/li/map-hs-label-value//span[@class='hs-attribute-value']"))).get_attribute("map-v-key"))
    
  • <span> 标签,文本为 89862530:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located()((By.XPATH, "//div[@class='hs-customerdata hs-customerdata-pvalues']/ul/li/map-hs-label-value//span[@class='hs-attribute-value']"))).get_attribute("innerHTML"))