I'm trying to code a python script using selenium to automatically pick something randomly for dinner by using the inputted location. However, I've been getting these error messages: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="tsuid11"]/div[2]/div/a/div/div[3]/div"}
I don't really understand why this error is happening. I've even watched the entire process load multiple times and am also certain the XPath value is correct.
This is my code:
import requests
import random
import time
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
location = input("Please enter your postal code: ")
driver = webdriver.Chrome("<path to chromedriver.exe>")
query = "food near " + location
print("Please give us a moment...")
driver.get("https://www.google.com/search?q=" + query)
time.sleep(3)
#this helps to click the "View All" option to see the entire list of restaurants nearby
view_all = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div/div/div[5]/div/g-more-link/a/div/span[1]')
view_all.click()
time.sleep(10)
#This is where I can't seem to find the element by its XPath
name = driver.find_element_by_xpath('//*[@id="tsuid11"]/div[2]/div/a/div/div[3]/div')
print(name)
driver.close()
I have also already searched this error up and got this: here
Based on the answer, the person mentioned "Could be a race condition where the find element is executing before it is present on the page". However, I've already added the time.sleep()
function to mitigate that.
Any help would be appreciated :)
Update: I got it to work by replacing find by XPath
to find by CSS Selector
. However, this is just a work around, I'm still going to try to figure this one out. Thanks for all the solutions, but unfortunately none of them worked for me.
- my View All button works perfectly fine on my end
- the webdriver wait function also didn't allow me to find the element (I think time.sleep does the exact same thing)
- and the element is not inside an iframe
After some further probing, I've tested the full XPath: /html/body/div[6]/div/div[7]/div[1]/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div[1]/div[4]/div[3]/div[2]/div/a/div/div[3]/div
on the browser console itself, and did not find anything. By digging through the layers, I've noticed that it stops at /html/body/div[6]/div/div[7]/div[1]/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div[1]/div[4]/div[3]/div[2]/div
, right before the a
tag. I'm not sure why as of now, will update again if I find anything.
Update 2: I used class name instead of XPath which is much more consistent for my output. That fixed everything for me :) Hope this helps.