如何从a网站中提取XHR响应数据?

2024-04-24 02:56:23 发布

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

我想得到一个链接到一种json文档,一些网页下载后得到加载。例如在this webpage上:

![![introducir la descripción de la imagen aquí

但在a different webpage上它可能是一个非常不同的文档。 很遗憾,我在Beautfiul soup的源页面中找不到链接。你知道吗

到目前为止我试过这个:

import requests
import json

data = {
  "Device[udid]": "",
  "API_KEY": "",
  "API_SECRET": "",
  "Device[change]": "",
  "fbToken": ""
}

headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"
}

url = "https://data.electionsportal.ge/en/event_type/1/event/38/shape/69898/shape_type/1?data_type=official"

r = requests.post(url, data=data, headers=headers)
data = r.json()

但它返回一个json解码错误:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-72-189954289109> in <module>
     17 
     18 r = requests.post(url, data=data, headers=headers)
---> 19 data = r.json()
     20 

C:\ProgramData\Anaconda3\lib\site-packages\requests\models.py in json(self, **kwargs)
    895                     # used.
    896                     pass
--> 897         return complexjson.loads(self.text, **kwargs)
    898 
    899     @property

C:\ProgramData\Anaconda3\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

C:\ProgramData\Anaconda3\lib\json\decoder.py in decode(self, s, _w)
    335 
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

C:\ProgramData\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Tags: andinpyselfnonejsondataparse
2条回答

这适用于您帖子中的两个链接:

from bs4 import BeautifulSoup
import requests
url = 'https://data.electionsportal.ge/en/event_type/1/event/38/shape/69898/shape_type/1?data_type=official'
r = requests.get(url)
soup = BeautifulSoup(r.text)
splits = [item.split('=',1)[-1] for item in str(soup.script).split(';')]
filtered_splits = [item.replace('"','') for item in splits if 'json' in item and not 'xxx' in item]
links_to_jsons = ["https://data.electionsportal.ge" + item for item in    filtered_splits]
for item in links_to_jsons:
   r = requests.get(item)
   print(r.json())       # change as you want      

顺便说一句,我猜你可以通过将69898改为另一个网页中位置相似的数字来构建json链接(但仍然是这样)data.electionsportal.ge). 你知道吗

您试图在HTML内容中找到的JSON由客户端通过javascript和XMLHttpRequests加载。这意味着您将无法使用BeautifulSoup在HTML中找到包含URL的标记,它在<script>块中或外部加载。你知道吗

此外,您正在尝试将用HTML编写的网页转换为JSON。并试图访问网页或JSON内容中未定义的密钥(coins)。。你知道吗

解决方案

  1. 直接加载这个JSON,而不需要在前面提到的网站中找到带有BeautifulSoup的JSON URL。这样,您就可以完美地运行requests.json()

  2. 否则,请查看Selenium,它是一个允许您运行javascript的web驱动程序。

希望这能解决问题。你知道吗

相关问题 更多 >