python - 为什么 Selenium 返回一个空文本字段?

标签 python selenium selenium-webdriver text

我正在尝试从 this page 中获取元素“total-price”的值.

我的 html 看起来像这样:

<div class="data">
<div class="data-first">Ydelse pr. måned</div>
<div class="data-last">
<span class="total-price">[3.551 Kr][1].</span>
</div>
</div>

我的代码如下:

monthlyCost = driver.find_element_by_xpath("//span[@class='total-price']")
print monthlyCost.text

奇怪的是该属性出现在网络元素中。

enter image description here

但是,如果我尝试打印它或将它分配给一个对象,它就会变成空的。为什么?

最佳答案

当你调试它时,你实际上是在添加一个暂停并无意中等待页面加载。

另外,价格是通过额外的 XHR 请求动态加载的,并且有一个中间“xxx”值,该值稍后在加载过程中被替换为实际值。事情变得越来越复杂,因为有多个具有 total-price 类的元素,并且只有其中一个变得可见。

我会用 custom Expected Condition 来处理它:

from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC

class wait_for_visible_element_text_to_contain(object):
    def __init__(self, locator, text):
        self.locator = locator
        self.text = text

    def __call__(self, driver):
        try:
            elements = EC._find_elements(driver, self.locator)
            for element in elements:
                if self.text in element.text and element.is_displayed():
                    return element
        except StaleElementReferenceException:
            return False

工作代码:

from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.leasingcar.dk/privatleasing/Citro%C3%ABn-Berlingo/eHDi-90-Seduction-E6G')

# wait for visible price to have "Kr." text
wait = WebDriverWait(driver, 10)
price = wait.until(wait_for_visible_element_text_to_contain((By.CSS_SELECTOR, "span.total-price"), "Kr."))
print price.text

打印:

3.551 Kr.

关于python - 为什么 Selenium 返回一个空文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776454/

相关文章:

python - 包装 Selenium "Expected Conditions"Python

selenium - 如何使用 Selenium WebDriver 从电子邮件中读取 OTP?

Java、Selenium、IntelliJ - 无法使用 DataFile.properties 中的变量

c++ - 我可以获得在键盘上按下某个键的时间量吗

python - 如何在Python中使用刷新 token Google API?

selenium - 无法点击 iframe 内的元素

c# - 找不到名为 webdriver.json 的文件或 ID 为“WebDriver.FirefoxPreferences”的嵌入式资源

java - 无法使用相对定位器单击第二个复选框

python - 将不同文件夹中的多个 csv 文件中的选定列合并到单个 csv 文件中

java - 如何为弹出窗口录制 Selenium 脚本?