代码之家  ›  专栏  ›  技术社区  ›  Krish Dewani

Django webscraping JSONDecodeError

  •  0
  • Krish Dewani  · 技术社区  · 3 年前

    我正在尝试抓取数据,例如,如果url的{fplid}值为30,它就可以正常工作。我该如何修复这个方法,这样它就可以从url获取用户输入和数据,而不会出现解码错误。这是回溯

    '''

    C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 31, in home
    data = get_html_content(fplid) …
    Local vars
    C:\Users\krish\OneDrive\Desktop\FPLHangout\scrape\views.py, line 9, in get_html_content
        managerdata = json.loads(r.text) 
    
    def get_html_content(fplid):
        url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/'
        r = requests.get(url)
        managerdata = json.loads(r.text)
        
        bootstrap = 'https://fantasy.premierleague.com/api/bootstrap-static/'
        bootstrapdata = requests.get(bootstrap)
        bootstrapjson = json.loads(bootstrapdata.text)
        for pick in managerdata['picks']:
            pick = (pick['element']) #correct id
            location = 0
            for player in bootstrapjson['elements']:
                if player.get('id') == pick:
                    break
                location += 1
            #position = (pick['position'])
            firstname = bootstrapjson['elements'][location]['first_name']
            secondname = bootstrapjson['elements'][location]['second_name']
            
        return firstname + " " + secondname
    
    
        def home(request):
            if 'fplid' in request.GET: #
                fplid = request.GET.get('fplid')
                data = get_html_content(fplid)
    
                return render(request, 'scrape/home.html', {'fpldata': data})
            return render(request, 'scrape/home.html')
    
    0 回复  |  直到 3 年前