我尝试使用urllib2模块修改用Python 2语言编写的代码。我在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))
答案 0 :(得分:2)
更改行
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
答案 1 :(得分:0)
@ 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
答案 2 :(得分:0)
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