0

I'm using Python for the first time to run a crawler. I've got the crawler to work and now I want to save the results in my MongoDB using pymongo,but for some reason I get this error: "NameError: name 'city' is not defined". If I wrap city in quotes,it works as expected,but I want to save it as it is. Anyone has done something similar or know what the solution is?

def gotHolidays(self, response):
        cityName = response.meta['name']
        feriado = []
        facult = []
        for selector in response.css("span.one"):
            feriado.append(selector.css("::text").extract())

        for selector in response.css("span.two"):
            facult.append(selector.css("::text").extract())

        city = {
            'city': cityName,
            'holidays':{
                'facult': facult,
                'feriado': feriado                
            }
        }
        print(json.dumps(city))

    from pymongo import MongoClient
    client = MongoClient()
    client = MongoClient ('localhost', 27017)
    db = client['myBank']
    myCollection = db.myCollection
    myCollection_data = {
        'cities': city
    }
    result = myCollection.insert_one (myCollection_data)
3
  • In which line are you getting the error? Commented Jul 20, 2018 at 12:30
  • 'cities': city. It says the name city is not defined Commented Jul 20, 2018 at 12:31
  • You seem to have a scope problem: issue is a dictionary that cannot be accessed outside of the gotHolidays() method. Or maybe it is just a formatting problem on StackOverflow? Commented Jul 20, 2018 at 12:38

1 Answer 1

1

The indentation looks wrong in your code snippet. The line from pymongo import ... should be at the same indentation level as the previous line:

        print(json.dumps(city))

        from pymongo import MongoClient
        client = MongoClient()

For python, indentation defines the scope. Un-indenting code is interpreted by python as 'end of the function'. Therefore, when you try to access the 'city' variable, it is no longer in scope

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.