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

2024-04-25 21:00:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从我的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值。在

我试过-

^{pr2}$

这将导致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,但不知道这一点。任何帮助都将不胜感激。在


Tags: divmapvaluehtmlattributelielementul
2条回答
  1. 您可以将带有文本SCN:^{}元素定位为//span[text()='SCN:']
  2. 文本为89862530的元素将是第1点元素的^{}
  3. 把所有东西放在一起:

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

    演示:

    enter image description here

参考文献:

SCN89862530的值反映在3个不同的位置,您可以从包含visibility_of_element_located()WebDriverWait的任何一个位置提取它,并且您可以使用以下任何一个Locator Strategies

  • 带有map-hs-lv-value属性的<map-hs-label-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"))
    
  • 带有map-v-key属性的<span>标记:

    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"))
    

相关问题 更多 >