【问题标题】:How to read a particular value from a web page in Python/Selenium如何在 Python/Selenium 中从网页中读取特定值
【发布时间】:2012-12-04 15:32:02
【问题描述】:

我想从此 HTML 中读取金额值 (24.40)。

<div id="order-total" class="clear-fix" style="margin-bottom:20px;">
    <h3 class="col-left">Order total</h3>
    <h3 class="col-right" style="display: block;">
    <span class="credit-total-to-order" data-total-to-order="24.40">$ 24.40</span>
    credits
    </h3>
</div>


xpath - /html/body/div/header/section/form/div[5]/h3[2]/span
css - html body.ui-lang-en div#slave-edit.string-v2 header#slave-edit-header.edit
      section#order-form form#frm-order-translation div#order-total.clear-fix 
      h3.col-right span.credit-total-to-order

我知道我应该使用find_element_by_class_namefind_element_by_css_selector
但不确定应该是什么论点。

我该怎么做?

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    为什么不从元素中选择值并解析字符串以获得您需要的答案。例如,您可以拆分字符串并忽略美元以返回您需要的数字。

    someString = selenium.find_element_by_css_selector(".credit-total-to-order").text
    someString.split(' ')[1]
    

    请记住 - 这适用于您提供的示例。

    【讨论】:

    • 要明确一点 - 当使用 css 选择器时,点表示法表示您正在寻找类名,因此 .someClass 会找到具有 class="someClass" 的元素
    • 这是一个 selenium 方法,从元素中提取文本并将其传递给变量,因此 someString 包含值“$ 24.40”
    • 我收到了这个错误。 NoSuchElementException: Message: u'Unable to locate element: {"method":"class name","selector":".credit-total-to_order"}'
    • 那是因为我的解决方案中有一个错字...现在已修复
    • 再次出错:ElementNotVisibleException: Message: u'Element is not currently visible and so may not be interacted with'
    【解决方案2】:

    没有必要使用find_element_by_class_name or find_element_by_css_selector..你可以像这样用xpath来实现它

    driver.find_element_by_xpath("//span[@class='credit-total-to-order']").text
    

    更新:

    根据您更新的 html,看起来样式使您的元素隐藏。意思是,我也注意到您想要获取的值也存储在属性 data-total-to-order 中。

    所以你可以这样做:

    driver.find_element_by_xpath("//span[@class='credit-total-to-order']").get_Attribute("data-total-to-order")
    

    【讨论】:

    • 同样的错误:ElementNotVisibleException: Message: u'Element is not currently visible and so may not be interacted with'
    • 能否请您粘贴完整的 html 代码以便更好地理解?
    • 添加了该组件的html源代码。
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2019-08-28
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多