Reputation: 159
My goal is to find a product listing by its name then click on it. Currently I want to iterate through all the text with the tag name h3 using a for loop and end the loop when the text is equal to the product I want. Now obviously, my code currently finds the very first listing then iterates through the characters in the string. What I want it to do is iterate through the different elements and pull out their text. I would appreciate any suggestions and will be quick to answer any questions. Thank you!
Code:
from selenium import webdriver
PATH = "/Users/devinhadley/Desktop/chromedriver"
driver = webdriver.Chrome(PATH)
driver.set_window_size(200, 200)
driver.get("https://shop-usa.palaceskateboards.com/")
elements = []
elements = driver.find_element_by_tag_name("h3").text
for element in elements:
print(element)
if element = "PERTEX PACKET JACKET GREY"
print("Done")
Upvotes: 1
Views: 973
Reputation: 27380
Try this:
from selenium import webdriver
PATH = "/Users/devinhadley/Desktop/chromedriver"
driver = webdriver.Chrome(PATH)
driver.set_window_size(200, 200)
driver.get("https://shop-usa.palaceskateboards.com/")
elements = driver.find_elements_by_tag_name("h3")
for element in elements:
if element.text == "PERTEX PACKET JACKET GREY":
print(element)
Update: I opened the webpage and I realized that find_elements_by_tag_name("h3")
won't work. The following will do:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
PATH = "/Users/devinhadley/Desktop/chromedriver"
driver = webdriver.Chrome(PATH)
driver.set_window_size(200, 200)
driver.get("https://shop-usa.palaceskateboards.com/")
elements=WebDriverWait(driver, 2).until(EC.visibility_of_all_elements_located((By.XPATH, '//div[@data-alpha]')))
for element in elements:
if element.get_attribute('data-alpha') == "PERTEX PACKET JACKET GREY":
print(element.get_attribute('data-alpha'))
element.click()
If you want to click on a particular element, you can either do element.click()
inside the for loop or elements[0].click()
, for example, if you want to click the first element.
Upvotes: 1