How to click on the first result on a dynamic page using python selenium?

348 Views Asked by At

I am trying to click on the first result on this page, but all the options I tried didn't work.

Firstly I just login into the website with email: [email protected] and password: Redfinpython06. Here is the code for it:

driver = webdriver.Chrome("C:\\Users\\kocia\\OneDrive\\Plocha\\Python\\nastaveni\\chromedriver.exe")
driver.get('https://www.redfin.com/myredfin/favorites')

email = '[email protected]'
password = 'Redfinpython06'

time.sleep(3)
driver.find_element_by_xpath(
    '//*[@id="content"]/div[6]/div/div[2]/div/div/form/span[1]/span/div/input').send_keys(email)

time.sleep(3)
driver.find_element_by_xpath(
    '//*[@id="content"]/div[6]/div/div[2]/div/div/form/span[2]/span/div/input').send_keys(password)

time.sleep(3)
sing_up = driver.find_element_by_css_selector('button[type=submit]')
sing_up.click()

But the problem is after login i can't click on the first result on the page.

Here is what i tried:

result = driver.find_elements_by_xpath("//*[@id="content"]/div[10]/div/div[5]/div/div[2]/div/div")[0]
result.find_element_by_xpath("//*[@id="content"]/div[10]/div/div[5]/div/div[2]/div/div/div[1]").click()

or

result = driver.find_elements_by_xpath("//*[@id="content"]/div[10]/div/div[5]/div/div[2]/div/div")[0]
result.click()

or

result = driver.find_element_by_xpath("//*[@id="content"]/div[10]/div/div[5]/div/div[2]/div/div/div[1]")
result.click()

Thank you so much for help.

1

There are 1 best solutions below

0
On BEST ANSWER

I hope that is a dummy email and password that you are just using for testing purposes :)

Below clicks on the first house picture in the list. I also cleaned up your email and password xpath designations. You can see how much easier it is to grab them by name

Also, you may want to put proper wait methods around these find elements. Using sleep generally is not recommended

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
from time import sleep


driver = webdriver.Chrome()
driver.get('https://www.redfin.com/myredfin/favorites')

email = '[email protected]'
password = 'Redfinpython06'

sleep(3)
driver.find_element_by_name(
    'emailInput').send_keys(email)

sleep(3)
driver.find_element_by_name(
    'passwordInput').send_keys(password)

sleep(3)
sing_up = driver.find_element_by_css_selector('button[type=submit]')
sing_up.click()
sleep(3)

first_house = driver.find_element_by_xpath("//div[@class='FavoritesHome'][1]//img")
first_house.click()