如何在div之外获取文字? [英] How to get text outside the div?
问题描述
<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>
我正在将selenium与python结合使用,并尝试从DOM中获取地址,但我做不到, 我用过
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"]'
捕获元素,但无法获取地址,因为您看到地址在//div元素之外 请注意,这是一个元素列表,然后我使用for循环在元素列表周围循环
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
推荐答案
提取地址,即 2420 E-Stadium Ann Arbor MI 48104 ,因为它是文本节点您需要使用execute_script()
方法为visibility_of_element_located()
引入 WebDriverWait ,并且可以使用以下任一
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:
-
使用
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())
使用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
这篇关于如何在div之外获取文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!