How to get text outside the div?

£可爱£侵袭症+ 提交于 2020-04-16 05:45:19

问题


<div class="amlocator-store-information" style="" xpath="1"> 
  <div class="amlocator-title" style="">The Better Health Store</div>
  2420 E-Stadium Ann Arbor MI 48104
  <br><br>
  (613) 975-6613
  <div style="" class="amasty_distance" id="amasty_distance_1">Distance:                            
    <span class="amasty_distance_number"></span>
  </div>
</div>

I am using selenium with python and trying to get the address from the DOM but I can't, I have used

store_block_list  = '//div[@class="amlocator-store-information"]'
store_block_list = '//div[@class="amlocator-title"]'

to capture the elements but cant get the address out as you can see the address is outside the //div element Please note it is a list of elements and I then use for loop to loop around the element list


回答1:


To extract the address i.e. 2420 E-Stadium Ann Arbor MI 48104 as it is a Text Node you need to induce WebDriverWait for the visibility_of_element_located() using execute_script() method and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.amlocator-store-information")))).strip())
    
  • Using XPATH:

    print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='amlocator-store-information']")))).strip())
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    


来源:https://stackoverflow.com/questions/60288910/how-to-get-text-outside-the-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!