[英]How Can I extract class value and save in csv using selenium?
How Can I extract the value using selenium and python, My end goal is to store this value in a csv.如何使用 selenium 和 python 提取值,我的最终目标是将此值存储在 csv 中。
What I have tried:我试过的:
#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)
But this returns an empty list?但这会返回一个空列表?
Looks like you are missing a wait / delay.看起来你错过了等待/延迟。
Try this尝试这个
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)
You will need these imports:您将需要这些导入:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
And to initialize the wait
object with并初始化wait
object 与
wait = WebDriverWait(driver, 20)
To print the innertexts eg $53.37
you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies :要打印内部文本,例如$53.37
,您需要为visibility_of_all_elements_located()引入WebDriverWait ,您可以使用以下任一定位器策略:
Using CLASS_NAME and get_attribute("innerHTML")
:使用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")))])
Using CSS_SELECTOR and get_attribute("textContent")
:使用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")))])
Using XPATH and text attribute:使用XPATH和文本属性:
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']")))])
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 relevant discussion in How to retrieve the text of a WebElement using Selenium - Python您可以在如何使用 Selenium - Python 检索 WebElement 的文本中找到相关讨论
Link to useful documentation:链接到有用的文档:
get_attribute()
method Gets the given attribute or property of the element.
get_attribute()
方法Gets the given attribute or property of the element.
text
attribute returns The text of the element.
text
属性返回The text of the element.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.