Home > Enterprise >  Variable throwing errors when inside find_element_by_id selenium python
Variable throwing errors when inside find_element_by_id selenium python

Time:09-27

I wrote this chunk of code

driver = webdriver.Chrome()
        siteURL = ("https://food.google.com/chooseprovider?restaurantId=/g/1tcxf3dw&hl=en- 
        US&gl=us&cs=1&ssta=1&fo_m=MfohQo559jFvMWwP9igWZeWQMczq7voErUdXMT_RFPQ05bfKMQVr5-7IofUJMU_hT8vrWuwRMUOzJVpjPL1YMfaXTPp5KXh-OAE=&gei=RPlNYdqNL-PB_Qb224zgCA&fo_s=OA,AH&orderType=2&sei=CXOeg4KHbv-eEWRLD3Wg9SOp&utm_campaign&utm_source=search")
driver.get(siteURL)
addFood = driver.find_element_by_id('-3088730200806839963')
addFood.click()

which I used to check to see if I can successfully find elements using their ids. It worked fine so then I decided to make it more efficient and created a json file which is this

{ 
    "food_apps": [
        {
            "Fried Calamari": "-3088730200806839963"
        },
        {
            "Our Famous Wings": "-1350800096379223241"
        },
        {
            "4 Piece Garlic Rolls": "-8109616989190485452"
        },
        {
            "5 Piece Mozzarella Sticks": "-3728727160150417226"
        },
        {
            "4 Piece Garlic Rolls With Sauce": "-1575357319596201105"
        },
        {
            "Eggplant": "-141455748912371356"
        },
        {
            "French Fries": "-5396459955060315412"
        },
        {
            "Broccoli Rabe": "3194878292893763893"
        },
        {
            "Onion Rings": "8601302989180579560"
        },
        {
            "Chicken Fingers With Fries": "-4477197721082407141"
        },
        {
            "Clams": "1350099334219961828"
        },
        {
            "Mussels": "-3470276416589467842"
        },
        {
            "Shrimp Basket": "-6884592797623295987"
        },
        {
            "Meatballs": "5243069348564888695"
        },
        {
            "Sausages": "1861088016475321205"
        },
        {
            "Eggplant Layers": "7657135224437837293"
        }
    ]
}

which I get a user input and match it to its respected ID value in the file with this code here

        n = 1

        for i in appOptions:
        
            print("#",n, ":", appOptions[n-1])
            n = n   1

        optionFood = int(input("What do you want to order? (enter the option #)"))
        time.sleep(2)
        optionFood = optionFood - 1
        appChoice = appOptions[optionFood]
        print("Do you want to add ", appChoice , "to your order?")
        y = input("(Enter 'y or n' to continue: )").lower()

        if y == "y" or "yes":
            f = open('food.json',)
            data = json.load(f)
        
            item = str(data['food_apps'][optionFood])
            itemID = item.split(':')[1].lstrip().split(' ')[0].lstrip('"').rstrip('"}')

after printing itemID, say I chose fried calamari I get as an output '-3088730200806839963' Which is what I want, but as soon as I try to swap the hard coded value in find_element_by_id() and make the statement

addFood = driver.find_element_by_id(itemID)

I get this error

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="'-3088730200806839963'"]"}
  (Session info: chrome=94.0.4606.61)

For help here is the code all together:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import json
import time

siteURL = ""

choiceOrder = input("Do you want to pick up your order or have it delivered? \n").lower()
time.sleep(2)
if (choiceOrder == "pick up" or "pickup" or "pick-up"):
    startFood = input('Do you want Appetizers, Salads, Pasta, Pizza, Entrees, or Hot & Cold Subs?').lower()
    if startFood == ("apps" or "appetizers"):
        appOptions = [
            "Fried Calamari",
            "Our Famous Wings",
            "4 Piece Garlic Rolls",
            "5 Piece Mozzarella Sticks",
            "4 Piece Garlic Rolls With Sauce",
            "Eggplant",
            "French Fries",
            "Broccoli Rabe",
            "Onion Rings",
            "Chicken Fingers With Fries",
            "Clams",
            "Mussels",
            "Shrimp Basket",
            "Meatballs",
            "Sausages",
            "Eggplant Layers"
            ]
        time.sleep(2)
        options = Options()
        options.headless = True
        driver = webdriver.Chrome()
        siteURL = ("https://food.google.com/chooseprovider?restaurantId=/g/1tcxf3dw&hl=en-US&gl=us&cs=1&ssta=1&fo_m=MfohQo559jFvMWwP9igWZeWQMczq7voErUdXMT_RFPQ05bfKMQVr5-7IofUJMU_hT8vrWuwRMUOzJVpjPL1YMfaXTPp5KXh-OAE=&gei=RPlNYdqNL-PB_Qb224zgCA&fo_s=OA,AH&orderType=2&sei=CXOeg4KHbv-eEWRLD3Wg9SOp&utm_campaign&utm_source=search")
        driver.get(siteURL)
        n = 1

        for i in appOptions:
        
            print("#",n, ":", appOptions[n-1])
            n = n   1

        optionFood = int(input("What do you want to order? (enter the option #)"))
        time.sleep(2)
        optionFood = optionFood - 1
        appChoice = appOptions[optionFood]
        print("Do you want to add ", appChoice , "to your order?")
        y = input("(Enter 'y or n' to continue: )").lower()

        if y == "y" or "yes":
            f = open('food.json',)
            data = json.load(f)
        
            item = str(data['food_apps'][optionFood])
            itemID = item.split(':')[1].lstrip().split(' ')[0].lstrip('"').rstrip('"}')
            print(str(itemID), "\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
            time.sleep(2)
            addFood = driver.find_element_by_id(itemID)
            addFood.click()


NOTE: I purposely didnt include options=options into the params so I can correctly debug what is happening.

CodePudding user response:

I can see issue with these two lines of code, and in error also you can witness the same.

item = str(data['food_apps'][optionFood])
            itemID = item.split(':')[1].lstrip().split(' ')[0].lstrip('"').rstrip('"}')

In the error you can easily see extra quote as you are type casting item to string. "[id="'-3088730200806839963'"] The possible solution will be use the item object as is as it would be a touple and you can do indexing there too. Below solution should work

itemID = data['food_apps'][optionFood][1]
             

CodePudding user response:

The IDs might get changed during run-time. Try catching the element you want with the following code:

element = driver.find_element_by_link_text("Fried Calamari")
element.click()
  • Related