我正在尝试从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
奇怪的是,该属性存在于Web元素中。
但是,如果我尝试打印它或将其分配给对象,则结果为空。为什么?
最佳答案
调试它时,实际上是在添加一个暂停,并且无意中等待页面加载。
另外,价格是通过附加的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/