1

I'm trying to modify a code which was written in Python 2 Language with the urllib2 module.I did modified my code with the module urllib in Python 3 but I'm getting error :

req = urllib.request(url)

TypeError: 'module' object is not callable

What I am doing wrong here?

import urllib.request
import json
import datetime
import csv
import time

app_id = "172"
app_secret = "ce3" 


def testFacebookPageData(page_id, access_token):

    # construct the URL string
    base = "https://graph.facebook.com/v2.4"
    node = "/" + page_id
    parameters = "/?access_token=%s" % access_token
    url = base + node + parameters

    # retrieve data
    req = urllib.request(url)
    response = urllib.urlopen(req)
    data = json.loads(response.read())

    print (json.dumps(data, indent=4, sort_keys=True))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Simon GIS
  • 1,045
  • 2
  • 18
  • 37

3 Answers3

2

Change the lines

req = urllib.request(url)
response = urllib.urlopen(req)

to:

req = urllib.request.Request(url)
response = urllib.request.urlopen(req)

You can find more information on this module **https://docs.python.org/3/library/urllib.request.html#urllib.request.Request **https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen

0

@kvmahesh's answer is absolutely correct. I'll just provide an alternate solution which supports both the versions. Use Python's requests library for making the call.

import requests
import json
import datetime
import csv
import time

app_id = "172"
app_secret = "ce3" 


def testFacebookPageData(page_id, access_token):

    # construct the URL string
    base = "https://graph.facebook.com/v2.4"
    node = "/" + page_id
    parameters = "/?access_token=%s" % access_token
    url = base + node + parameters

    # retrieve data
    response = requests.get(url)
    data = json.loads(response.text())

    print (json.dumps(data, indent=4, sort_keys=True))

For detailed usage of requests: Python Requests Docs

Rakmo
  • 1,926
  • 3
  • 19
  • 37
0

urllib.request is a module. You are calling the module on line 22...

req = urllib.request(url)

To fix do following:

1) Import at the top:

from urllib.request import urlopen

2) then pass the url to urlopen(url)

# remove this line req = urllib.request(url)
response = urlopen(url)
data = json.loads(response.read())

3) See similar error here TypeError: 'module' object is not callable