因此,我试图制作一个脚本来在网站上发出请求,然后比较是否有新项目添加到请求中,这意味着是否有新项目-请提醒我,如果没有。在几分钟内请求访问同一页面。
所以我现在遇到的问题是实际打印到一个告诉我的列表:
TypeError: string indices must be integers
但是每当我打印元素时,它只会给我打印“ id”,我不明白原因-
代码外观:
resp = s.get(url)
list = []
i = 0
for element in resp.json()['threads']['product']:
print(element) #<--- this gives me a print of "id"
list.append(element['fullTitle'])
#ERROR - list.append(element['fullTitle'])
#TypeError: string indices must be integers
i+=1
print(list)
while True:
try:
new_list = []
url = 'https://hellowebsite.com'
resp = s.get(url)
for element in resp.json()['threads']['product']:
new_list.append(element['fullTitle'])
print(new_list)
for link in new_list:
if link not in list:
print('New item found! - ' + link)
else:
print("No new itemfound!")
time.sleep(10)
except:
randomtime = random.randint(6, 12)
Json代码:(它尚未完全完成,但看起来像这样)
{
"country": "GB",
"locale": "Thrill",
"threads": [{
"id": "f44291998750ce50301f36607c7996b5db5a9c3b",
"interestId": "57d4d929-694c-4fdd-9277-f0df465cd7c7",
"createdDate": "2018-06-26T08:05:24.000",
"product": {
"id": "b0bfdaa1-140c-54de-b040-66854ec62d1b",
"interestId": "a53256c1-983b-43d5-895c-c5b7c3eedc85",
"colorCode": "100",
"fullTitle": "Item Number 1",
}
},
{
"id": "0c132053034f79c08dd474d6371875fe421e8694",
"interestId": "ceb1c5f5-4ff2-43f4-8330-d537d1a4f5f9",
"createdDate": "2018-06-26T08:24:42.000",
"product": {
"id": "2b7830e3-2e36-54cd-a290-29c38493b290",
"interestId": "8aaeb398-91d6-45f1-b0d0-f4e8561e62fb",
"colorCode": "800",
"fullTitle": "Item Number 2",
}
},
{
"id": "985ff4b1bb969dd7a95ea589aff4d5f4710ab69e",
"interestId": "aa73be8b-793e-4d78-b512-e80e2a019599",
"createdDate": "2018-06-25T10:20:47.000",
"product": {
"colorCode": "001",
"fullTitle": "Item number 3",
}.....
能将所有fullTitle打印出一个列表然后继续进行比较的建议是什么?
编辑全曲
resp = s.get(url)
for element in resp.json()['threads']['product']['fullTitle']:
print(element)
错误
Process Process-1:
Traceback (most recent call last):
File "C:\Users\Username\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 249, in _bootstrap
self.run()
File "C:\Users\Usersname\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Test.py", line 84, in script
for element in resp.json()['threads']['product']['fullTitle']:
TypeError: list indices must be integers or slices, not str
答案 0 :(得分:3)
您正在遍历错误的内容。这里的列表是“线程”,其中的每个元素都有一个“产品”字典,其中包含“ fullTitle”元素。所以您要遍历:
for thread in resp.json()['threads']
print(thread['product']['fullTitle'])