如何解决获取html span硒python中的值
binary.com上的某个跨度图标具有以下html代码:
<span id="spot" style="" data-value="3862.76" class="price_moved_down">3,862.76</span>
其中数据值每2秒更改一次。我想在我的Web自动化脚本中使用该数据值,但是我不知道从哪里开始,请帮忙。请参阅图片以了解。
解决方法
要打印文本 3,862.76 ,您可以使用以下任一Locator Strategies:
-
使用
css_selector
和get_attribute()
:print(driver.find_element_by_css_selector("span.price_moved_down#spot[data-value]").get_attribute("innerHTML"))
-
使用
xpath
和 text 属性:print(driver.find_element_by_xpath("//span[@class='price_moved_down' and @id='spot'][@data-value]").text)
理想情况下,要打印文本 3,862.76 ,您必须为visibility_of_element_located()
引出WebDriverWait,并且可以使用以下任一Locator Strategies:
-
使用
CSS_SELECTOR
:print(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"span.price_moved_down#spot[data-value]"))).get_attribute("innerHTML"))
-
使用
XPATH
:print(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH,"//span[@class='price_moved_down' and @id='spot'][@data-value]"))).text)
-
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在How to retrieve the text of a WebElement using Selenium - Python
中找到相关的讨论
Outro
链接到有用的文档:
-
get_attribute()
方法Gets the given attribute or property of the element.
-
text
属性返回The text of the element.
- Difference between text and innerHTML using Selenium
数字是元素的文本值。所以一旦找到使用硒的元素
my_span = driver.find_element_by.....
您可以在元素上调用text属性
print(my_span.text)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。