Python 2 to Python 3 : TypeError: 'module' object is not callable

Python 2 to Python 3 : TypeError: 'module' object is not callable

我正在尝试使用 urllib2 修改用 Python 2 语言编写的代码 module.I 确实使用 Python 3 中的模块 urllib 修改了我的代码,但我'我收到错误:

req = urllib.request(url)

TypeError: 'module' object is not callable

我这里做错了什么?

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))

换行

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

至:

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

您可以找到有关此模块的更多信息**https://docs.python.org/3/library/urllib.request.html#urllib.request.Request **https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen

@kvmahesh 的回答完全正确。我将只提供一个支持这两个版本的替代解决方案。使用 Python 的 requests 库进行调用。

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))

请求的详细用法:Python Requests Docs

urllib.request 是一个模块。您正在第 22 行调用模块...

req = urllib.request(url)

要修复,请执行以下操作:

1) 在顶部导入:

from urllib.request import urlopen

2) 然后将 url 传递给 urlopen(url)

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

3) 在此处查看类似错误 TypeError: 'module' object is not callable