python请求url以获取记录simplejson.errors.JSONDecodeError:

2024-04-26 17:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python中使用requests方法获取表记录。它可以很好地处理其他URL请求,但我在代码中提到的URL实际上是生物识别机器数据,以表的形式显示在链接中。我已经提到了下面的代码,请检查,让我知道有一个可能的解决方案。实际上我想获取考勤记录导入请求导入sys,JSON 导入请求 导入sys,JSON

 import json
 import requests
 import urllib
 url = "http://pokemondb.net/pokedex/all"

 data = requests.get(url).json()
 print(str(data.status_code))
 if data.status_code == 200:
    print(str(data.json()))

错误

Traceback (most recent call last): File "/home/arslan/Documents/Dynexcel/http_request_html_table/http_request.py", line 7, in data = requests.get(url).json() File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "/usr/lib/python3/dist-packages/simplejson/init.py", line 518, in loads return _default_decoder.decode(s) File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode obj, end = self.raw_decode(s) File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 400, in raw_decode return self.scan_once(s, idx=_w(s, idx).end()) simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


Tags: inpyimportjsondatalibpackagesusr
1条回答
网友
1楼 · 发布于 2024-04-26 17:30:36

我希望我没有遗漏什么,但是您试图从中检索数据的网站显然是html而不是json。python在第行给出了一个解码错误:

 requests.get(url).json()

因此,您有多个选项来解析此html和提取数据。一种选择是通过请求获取html,然后使用bs4提取数据。 顺便说一下,我在这个网站上没有看到任何“出勤”栏目。下面是一个代码示例,它获取了最高的总分和相关口袋妖怪的名称:

import json
import requests
import urllib
from bs4 import BeautifulSoup
url = "http://pokemondb.net/pokedex/all"

all_pokemons = []
all_scores = []

data = requests.get(url)

soup = BeautifulSoup(data.text, 'html.parser')

all_td = soup.findAll("td", {"class": "cell-total"})

all_pokemon_hrefs = soup.findAll("a", {"class":"ent-name"})




for pokemon in all_pokemon_hrefs:

    all_pokemons.append(pokemon.renderContents().decode("utf-8"))

for td in all_td:

    all_scores.append(td.renderContents().decode("utf-8"))


print("Pokemon {} has the highest total score with: {}".format(str(all_pokemons[all_scores.index(max(all_scores))]),str(max(all_scores))))

相关问题 更多 >