如何使用 selenium 和 python 提取值,我的最終目標是將此值存盤在 csv 中。
我嘗試過的:
#element= driver.find_element_by_xpath("//*[@class='rt-tr-group']")
elements = driver.find_elements_by_class_name("product-form__price")
for value in elements:
print(value.text)
但這會回傳一個空串列?
HTML
uj5u.com熱心網友回復:
看起來您錯過了等待/延遲。
試試這個
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".product-form__price")))
time.sleep(0.5)
elements = driver.find_elements_by_class_name("product-form__price")
for value in elements:
print(value.text)
您將需要這些匯入:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
并wait用
wait = WebDriverWait(driver, 20)
uj5u.com熱心網友回復:
要列印內部文本,例如,$53.37 您需要為visibility_of_all_elements_located()引入WebDriverWait,您可以使用以下任一定位器策略:
使用CLASS_NAME和
get_attribute("innerHTML"):print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "product-form__price")))])使用CSS_SELECTOR和
get_attribute("textContent"):print([my_elem.get_attribute("textContent") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.product-form__price")))])使用XPATH和text屬性:
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//span[@class='product-form__price']")))])注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在How toret the text of a WebElement using Selenium - Python 中找到相關討論
參考
鏈接到有用的檔案:
get_attribute()方法Gets the given attribute or property of the element.text屬性回傳The text of the element.- 使用 Selenium 的 text 和 innerHTML 之間的區別
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385900.html
