2015-08-02 10 views
5

मैं this page से "कुल मूल्य" तत्व का मूल्य प्राप्त करने का प्रयास कर रहा हूं।सेलेनियम एक खाली टेक्स्ट फ़ील्ड क्यों लौटाता है?

मेरे एचटीएमएल इस तरह दिखता है: इस प्रकार

<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 

अजीब बात संपत्ति webelement में मौजूद है।

enter image description here

हालांकि, अगर मैं कोशिश करते हैं और इसे प्रिंट या किसी वस्तु के लिए असाइन करें यह खाली बाहर आता है। क्यूं कर?

उत्तर

6

जब आप इसे डीबग करते हैं, तो आप वास्तव में एक विराम जोड़ रहे हैं और अनजाने में पेज लोड होने की प्रतीक्षा कर रहे हैं।

प्लस, कीमत अतिरिक्त एक्सएचआर अनुरोध के साथ गतिशील रूप से लोड की जाती है और इसमें मध्यवर्ती "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. 
+0

@alexce - धन्यवाद! – Frank

संबंधित मुद्दे