[英]Python Selenium: Can get web's element but cannot get the text in it
https://www.futunn.com/en/stock/FUTU-US這個網頁,說我想得到浮點值
# -*- coding: utf-8 -*-
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
PATH='C:\\Users\\admin\\Documents\\chromedriver.exe'
driver = webdriver.Chrome(PATH,chrome_options=options)
driver.get('https://www.futunn.com/en/stock/FUTU-US')
freeflowtickers=driver.find_element_by_xpath("//*[@id=\"app\"]/div/div[3]/section[1]/div[4]/div[9]/div[4]/div[2]")
print(freeflowtickers)
print(freeflowtickers.text)
然后運行它,在控制台中,你得到
<selenium.webdriver.remote.webelement.WebElement (session="08bc2133e5e3b6911cea32c6750833a8", element="e38cb418-2e37-428d-af4b-e01dd3e691ae")>
但是在它之后沒有文本被獲取。
這怎么可能發生?
所以這不是最干凈的解決方案,但我只是測試了它並且它正在工作。
float_element = driver.find_element_by_xpath('//*[@id="app"]/div/div[3]/section[1]/div[4]/div[9]/div[4]')
number = float_element.text.split("\n")[1]
我已經抓取了父 div 標簽的 xpath,其中包含兩行文本“Float”和由換行符分隔的數字。
要打印文本64.11M ,您可以使用以下任一Locator Strategies :
使用xpath和get_attribute("innerHTML")
:
print(driver.find_element(By.XPATH, "//div[text()='Float']//following-sibling::div[1]").get_attribute("innerHTML"))
使用xpath和文本屬性:
print(driver.find_element(By.XPATH, "//div[text()='Float']//following-sibling::div[1]").text)
理想情況下,您需要為visibility_of_element_located()引入WebDriverWait ,並且您可以使用以下任一Locator Strategies :
使用XPATH和文本屬性:
driver.get("https://www.futunn.com/en/stock/FUTU-US") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='stock-detail-btn']/i"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Float']//following-sibling::div[1]"))).text)
使用XPATH和get_attribute("innerHTML")
:
driver.get("https://www.futunn.com/en/stock/FUTU-US") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='stock-detail-btn']/i"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Float']//following-sibling::div[1]"))).get_attribute("innerHTML"))
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
鏈接到有用的文檔:
get_attribute()
方法Gets the given attribute or property of the element.
text
屬性返回The text of the element.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.