简体   繁体   中英

Unable to locate elements in Selenium (using xpath) python within Instagram

I'm trying to click an element using selenium but for some reason I keep running into this error using Xpath.

from time import sleep
from selenium import webdriver

driver_path = "C:\WebDrivers\chromedriver"
driver = webdriver.Chrome(driver_path)
driver.implicitly_wait(5)
driver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')

sleep(2)

username = driver.find_element_by_name('username')
username.send_keys('YourEmail')
password = driver.find_element_by_name('password')
password.send_keys('YourPassword')

submit =driver.find_element_by_tag_name('form')
submit.submit()

driver.implicitly_wait(15)

explore = driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[4]/a/svg/path')
explore.click()

The issue occurs on my last two lines of code. The Xpath comes from following html line:

<path clip-rule="evenodd" d="M24 0C10.8 0 0 10.8 0 24s10.8 24 24 24 24-10.8 24-24S37.2 0 24 0zm0 45C12.4 45 3 35.6 3 24S12.4 3 24 3s21 9.4 21 21-9.4 21-21 21zm10.2-33.2l-14.8 7c-.3.1-.6.4-.7.7l-7 14.8c-.3.6-.2 1.3.3 1.7.3.3.7.4 1.1.4.2 0 .4 0 .6-.1l14.8-7c.3-.1.6-.4.7-.7l7-14.8c.3-.6.2-1.3-.3-1.7-.4-.5-1.1-.6-1.7-.3zm-7.4 15l-5.5-5.5 10.5-5-5 10.5z" fill-rule="evenodd"></path>

I'm not sure but maybe this has something to do with the fact that it is subcategorized under <svg>

See screenshot:

1

The desired element is within a <svg> tag, so to click on the element you can use either of the following Locator Strategies :

  • Using css_selector :

     driver.find_element(By.CSS_SELECTOR, "svg[aria-label='Find People'] > path[clip-rule='evenodd'][fill-rule='evenodd']").click()
  • Using xpath :

     driver.find_element(By.XPATH, "//*[name()='svg' and @aria-label='Find People']//*[name()='path' and @clip-rule='evenodd']").click()

Ideally, you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[aria-label='Find People'] > path[clip-rule='evenodd'][fill-rule='evenodd']"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label='Find People']//*[name()='path' and @clip-rule='evenodd']"))).click()
  • 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

References

You can find a couple of relevant detailed discussions in:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM