如何使用Python Selenium Webdriver获取li内span的值?

时间:2019-06-12 08:26:13

标签: python selenium-webdriver xpath webdriverwait xpath-1.0

我正在尝试从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的新手,无法弄清楚这一点。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

SCN的值(即 89862530 )反映在3个不同的位置,您可以从两个引发 WebDriverWait 的位置提取{{1 }},您可以使用以下任一Locator Strategies

    具有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

答案 1 :(得分:0)

  1. 您可以找到span元素,其文本为SCN:,文字为//span[text()='SCN:']
  2. 文本为89862530的元素将是从点1开始的元素的following-sibling
  3. 将所有内容放在一起:

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

    演示:

    enter image description here

参考文献:

相关问题