![](/img/trans.png)
[英]How to extract the texts from the span tag as per the html using selenium and Python
[英]How to locate or extract texts in html file using selenium in python?
如何在 Python 中使用 Selenium 定位或提取 HTML 文件中的文本。 我试图获得的文本不是一个元素。
<div class="datagrid row"> ==$0
<h2 class="bottom-border block">Accepted Shipment</h2>
<table>
<tbody>
<tr>
<td>
<input type="hidden" id="looseAcceptedPieces" value="56"> == $0
" 56 pcs."
<!--Modified by A-7558 for ICRD-244765 starts--> == $0
<input type="hidden" id="acceptedWt" value> == $0
"952 kg"
我如何在<input>
下找到或获取该文本,即56 个。 和952 公斤也许,他们不是元素。
您可以使用get_attribute("value")
方法获取值
piece = driver.find_element_by_id('looseAcceptedPieces')
val = piece.get_attribute("value")
和
weight = driver.find_element_by_id('acceptedWt')
val2 = weight.get_attribute("value")
提取文本56 个。 和952 kg,因为这些是您需要使用execute_script()
方法为visibility_of_element_located()
引入WebDriverWait 的文本节点,您可以使用以下基于xpath的定位器策略之一:
提取56 个。 :
print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='Accepted Shipment']//following::table[1]/tbody/tr/td")))).strip())
提取952 公斤:
print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='Accepted Shipment']//following::table[1]/tbody/tr/td")))).strip())
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到相关讨论:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.