Store text of driver.find_element into a python variable

Question:

Im trying to create an discord embed that containts info of some webstite. Im trying to store the driver.find_element.text of with selenium.

Then I want to put that python variable into a json code that makes a discord embed.

The problem is that each product of this page give me 3 different texts. How can I save each one in diferents variables. I put my code here
`

from selenium import webdriver
from selenium.webdriver.common.by import By
import csv

DRIVER_PATH = 'C:chromedriver.exe'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get('https://www.zalando.es/release-calendar/zapatillas-mujer/')

product_1 = driver.find_element(By.XPATH, '//*[@id="release-calendar"]/div/div[1]/div')
print(product_1.text)

The result in terminakl is
119,95€
adidas Originals
Forum MID TM
28 de octubre de 2022, 8:00
Recordármelo

Thanks for the help I really dont know how to save the .text info into differents python varaibles.

Asked By: Expoespa

||

Answers:

Store the text in a variable or a

element_text = product_1.text
element_text_split = element_text.split()  # split by space

If you wanted the price of that item: element_text_split[0] would get the first word

Second word element_text_split[1] is the company

You could also slice up the string using string slicing. Keep in mind not all data you get is going to look exactly the same.

Answered By: Zack Walton

This is what I’ve used in the past but that’s assuming you have a specific element attribute which you’re trying to extract:

For example:

element_text = driver.find_element(By.XPATH, '//*[@id="release-calendar"]/div/div[1]/div').get_attribute('title')

You’ll need to replace 'title' with the specific attribute from your element which contains the text you want.

Answered By: Denis N.

So, you are trying to get texts of each product on the page, right?
If so, you can use find_elements() method to put all the products on the page into a list. For that you need to use an xpath (or any other locator) that finds not one element but all of them.
Here is the code

from selenium import webdriver
from selenium.webdriver.common.by import By


driver = webdriver.Chrome()
driver.get('https://www.zalando.es/release-calendar/zapatillas-mujer/')

# This finds all products on the page and puts them into a list of elements:
products = driver.find_elements(By.XPATH, '//div[@class="auWjdQ rj7dfC Hjm2Cs _8NW8Ug xJbu_q"]')

# This will put text of each product into a list
texts = []
for product in products:
    texts.append(product.text)

# Here we can see what is in the list of texts
print('All texts:', texts)

# If list doesn't suite your needs, you can unpack the list into three variables
# (only if you are sure that there are only three items on the page):
prod1, prod2, prod3 = texts
print('Product 1:', prod1)
print('Product 2:', prod2)
print('Product 3:', prod3)
driver.quit()
Answered By: Eugeny Okulik