我试图获得元素的价值"总价格"来自this page。
我的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
奇怪的是财产存在于财产中。
但是,如果我尝试打印它或将其分配给一个对象,它就会变空。为什么呢?
答案 0 :(得分:7)
调试时,您实际上是在添加暂停并无意中等待页面加载。
另外,价格是通过额外的XHR请求动态加载的,并且有一个中间的&#34; xxx&#34;在加载过程中稍后用实际值替换的值。事情变得越来越复杂,因为有多个total-price
类的元素,只有其中一个元素变得可见。
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.