td中的Python/Selenium文本,不含span文本

2024-04-16 04:58:39 发布

您现在位置:Python中文网/ 问答频道 /正文

html代码是

<td>
    <i class="fas fa-arrow-down arrow-green"></i>
    <span class="fs_buy">Strong Buy</span> 
    1.11
</td>

如果我使用这个代码

cccss ='//*[@id="fs_title_values"]/div[3]/table/tbody/tr[1]/td[5]'
about = driver.find_element_by_xpath(cccss)
RatingCurrentValue=about.text
print ('RatingCurrentValue', RatingCurrentValue)

我将得到所有文本:RatingCurrentValue Strong Buy 1.11

我的目标是只获得1.11版本,而不在span标记中添加文本

请帮帮我


Tags: 代码文本htmlbuyfsclassfatd
3条回答

可以从全文中删除子节点文本以获取父节点文本

cccss ='//*[@id="fs_title_values"]/div[3]/table/tbody/tr[1]/td[5]'


full_text = driver.find_element_by_xpath(cccss).text

child_text = driver.find_element_by_xpath(cccss + “//span”).text

parent_text = full_text.replace(child_text, '')
print(parent_text)

要获取值1.11,请使用javascripts executor并获取td元素的lastChild

诱导WebDriverWait()visibility_of_element_located()

element=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="fs_title_values"]/div[3]/table/tbody/tr[1]/td[5]')))
print(driver.execute_script('return arguments[0].lastChild.textContent;', element))

您需要添加以下库

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

更新

print(driver.execute_script('return arguments[0].lastChild.textContent;', driver.find_element_by_xpath('//*[@id="fs_title_values"]/div[3]/table/tbody/tr[1]/td[5]')))

从元素中提取文本1.11,您可以使用以下基于的解决方案:

print(driver.find_element_by_xpath("//td[//span[@class='fs_buy' and text()='Strong Buy']]").get_attribute("innerHTML").splitlines()[2])

理想情况下,必须为visibility_of_element_located()诱导WebDriverWait,并且可以使用以下基于Locator StrategiesXPATH

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[//span[@class='fs_buy' and text()='Strong Buy']]"))).get_attribute("innerHTML").splitlines()[2])

注意:您必须添加以下导入:

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

相关问题 更多 >