Home > database >  How to click on link where there is image in front in python using webdriver?
How to click on link where there is image in front in python using webdriver?

Time:03-18

I am trying to click on the link behind the image on eBay.

Code

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time
url='https://www.ebay.com/sch/i.html?_from=R40&_nkw=Pet Sim X 1B 25B 100B 250B Gems/diamonds Pet Simulator X Cheep+Instant Delivery&_sacat=0&_fcid=1'
driver = webdriver.Chrome("E:\chromedriver.exe")
driver.maximize_window()
driver.minimize_window()
driver.maximize_window()
time.sleep(2)
driver.get(url)
#Gets all the elements of images on page
titles=driver.find_elements(By.XPATH,'//img[@]')
time.sleep(2)
#gets the element of first image
element=titles[0]
#clicks
ActionChains(driver).move_to_element(element).click().perform()
time.sleep(10)
driver.close()

So what it does is collects all elements of the image in a list and then I can click any specific element/IMG by just giving list index

URL

I can't click the image it should open a new tab but it doesn't please help me. Thank You

CodePudding user response:

The XPath locator you are using here is not good enough.
Instead of

titles=driver.find_elements(By.XPATH,'//img[@]')

Please use

titles=driver.find_elements(By.XPATH,'//div[@id="srp-river-results"]//img[@]')

This will give you correct results.
You should also remove the redundant driver.maximize_window() and use Expected Conditions explicit waits instead of hardcoded pauses like time.sleep(2)

CodePudding user response:

I see only one image in the link: Snapshot and for this, you can use this:

driver.get("https://www.ebay.com/sch/i.html?_from=R40&_nkw=Pet Sim X 1B 25B 100B 250B Gems/diamonds Pet Simulator X Cheep+Instant Delivery&_sacat=0&_fcid=1")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//img[@])[2]'))).click()
  • Related