【发布时间】:2021-10-16 04:12:24
【问题描述】:
python 代码: 如您所见,我编写的代码有问题,请帮助我
import requests
import json
import psycopg2
import urllib
from urllib.request import Request, urlopen
con = psycopg2.connect(database='test', user='postgres', password='affan@123', host='localhost', port='5432')
cursor = con.cursor()
url = 'https://api.imgflip.com/get_memes'
page=urllib.request.Request(url,headers={'User-Agent': 'chrome'})
response = urllib.request.urlopen(page).read()
json_obj = str(response, 'utf-8')
json_obj = json.loads(response.decode('utf-8'))
cursor.execute(
"""create table if not exists memes_data(
id text, name text, url text, width integer, height integer, box_count integer);"""
)
for obj in json_obj:
print(obj["id"])
print(obj["name"])
print(obj["url"])
print(obj["width"])
print(obj["height"])
print(obj["box_count"])
cursor.execute("INSERT INTO memes_data (id, name, url, width, height, box_count) VALUES (%s,%s,%s,%s,%s,%s)", (obj["id"], obj["name"], obj["url"], obj["width"], obj["height"], obj["box_count"]))
con.commit()
con.close()
运行时出错 你看到的错误是字符串索引必须是整数,我该怎么办?
Traceback (most recent call last):
File "c:\Users\shaik\Desktop\api ex\ob.py", line 22, in <module>
print(obj["id"])
TypeError: string indices must be integers
【问题讨论】:
-
请注意,当您遍历字典时,您正在遍历键。如果你只是想打印和使用这些值,你可以这样做:
for v in json_obj.values():.
标签: python json postgresql insert