I am studying mongoDB with python, I met this problem.
When I tried to open a url by python, I copied some code from internet like following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import json import urllib2 import pymongo # connect to mongo connection = pymongo.MongoClient("mongodb://localhost") # get a handle to the reddit database db = connection.reddit stories = db.stories # drop existing collection stories.drop() # get the reddit home page reddit_page = urllib2.urlopen("https://www.reddit.com/r/technology/.json") # parse the json into python objects parsed = json.loads(reddit_page.read()) # iterate through every news item on the page for item in parsed['data']['children']: # put it in mongo stories.insert_one(item['data']) |
and met this error:
NameError: name urllib2 is not defined
Then I found that ‘urllib2’ is a lib for python2 while I use python3
Solution is easy by changing import lib
1 2 3 |
import urllib.request reddit_page = urllib.request.urlopen("https://www.reddit.com/r/technology/.json") |