How to retrieve partial text from a text node using Selenium and Python(如何使用 Selenium 和 Python 从文本节点中检索部分文本)
问题描述
我只想获取文本..."而不使用 .split() 或索引切片
I want to get only " text ... " not using .split() or index slicing
HTML:
<a class="call_recipe" href="/recipes/2913">
" text ... "
<strong> something~ </strong>
</a>
HTML 快照:
推荐答案
要打印 text ... 你必须诱导 WebDriverWait 用于 visibility_of_element_located()
并且您可以使用以下任一 定位器策略:
To print text ... you have to induce WebDriverWait for the visibility_of_element_located()
and you can use either of the following Locator Strategies:
使用
CSS_SELECTOR
、childNodes 和strip()
:
print(driver.execute_script('return arguments[0].firstChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.call_recipe[href^='/recipes']")))).strip())
使用 XPATH
、get_attribute()
和 splitlines()
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='call_recipe' and starts-with(@href, '/recipes')]"))).get_attribute("innerHTML").splitlines()[1])
注意:您必须添加以下导入:
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
您可以在以下位置找到一些相关的详细讨论:
You can find a couple of relevant detailed discussions in:
- 如何获取特定文本属于 div 类
- 如何使用 Selenium 和 Python 从由空格分隔的文本节点获取文本
这篇关于如何使用 Selenium 和 Python 从文本节点中检索部分文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Selenium 和 Python 从文本节点中检索部分


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01