我一直在尝试解析python中的json"字符串索引必须是整数"

时间:2016-07-18 04:17:01

标签: python json parsing

当我使用json.loads时,我收到以下错误

string indices must be integers

我正在做一些研究,看到有人认为我的情况类似。我改变了这个

json.dumps(newstring_two)

到这个

json.loads(json.dumps(newstring_two))

但它仍然无效。这是我创建的功能

def panties():
        pan_url = 'http://www.panvideos.com'
        html = requests.get(pan_url, headers=headers)
        soup = BeautifulSoup(html.text, 'html5lib')
        video_row = soup.find_all('div', {'class': 'video'})

        def youtube_link(url):
            youtube_page = requests.get(url, headers=headers)
            soupdata = BeautifulSoup(youtube_page.text, 'html5lib')
            video_row = soupdata.find('div', {'class': 'video-player'})
            entries = [{'text': str(div),
                        } for div in video_row][3]['text']

            oldstring = str(entries)
            removed = '<script type="text/javascript">jwplayer("video-setup").setup('
            newstring = oldstring.replace(removed, "")
            removed_two = ');</script>'
            newstring_two = newstring.replace(removed_two, "")
            parsed_json = json.dumps(newstring_two)
            finishe = parsed_json['file']

            return finishe

        entries = [{'text': div.h4.text,
                    'href': div.a.get('href'),
                    'tube': youtube_link(div.a.get('href')),
                    } for div in video_row][:1]

        return entries

但它没有用。问题是什么?

编辑:我的完整追溯

        Traceback (most recent call last):
      File "/Users/ray/Desktop/oku/practice/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
        response = self.process_exception_by_middleware(e, request)
      File "/Users/ray/Desktop/oku/practice/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/Users/ray/Desktop/oku/super_nu/src/blog/views.py", line 164, in index
        pan = panties()
      File "/Users/ray/Desktop/oku/super_nu/src/blog/my_scraps.py", line 166, in panties
        } for div in video_row][:1]
      File "/Users/ray/Desktop/oku/super_nu/src/blog/my_scraps.py", line 166, in <listcomp>
        } for div in video_row][:1]
      File "/Users/ray/Desktop/oku/super_nu/src/blog/my_scraps.py", line 159, in youtube_link
        finishe = parsed_json['file']
    TypeError: string indices must be integers

2 个答案:

答案 0 :(得分:1)

&#39; newstring_two&#39;是字符串,因此parsed_json = json.dumps(newstring_two)应替换为parsed_json = json.loads(newstring_two)。 见JSON encoder and decoder

答案 1 :(得分:0)

您应该使用整数而不是&#39;文件&#39;该行的陈述:

finishe = parsed_json['file']

所以,可以这样:

finishe = parsed_json[0]

示例中的0数字可以是1,2,3,4 .....你必须找出哪个是真数。