我想获得指向某种json文档的链接,某些网页在加载后会下载。例如在this webpage上:
但这可能是a different webpage上的一个完全不同的文档。 不幸的是,我在源页面中找不到Beautfiul汤的链接。
到目前为止,我已经尝试过:
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)
答案 0 :(得分:0)
您尝试在HTML内容中找到的JSON由客户端通过带有XMLHttpRequests的javascript加载。这意味着您将无法使用BeautifulSoup在包含URL的HTML中找到标记,该标记位于<script>
块内部或外部。
此外,您正在尝试将用HTML编写的网页转换为JSON。并尝试访问在网页或JSON内容中未定义的键( coins )。
解决方案
直接加载该JSON,而无需尝试在上述网站中使用BeautifulSoup查找JSON URL。这样,您就可以完美运行requests.json()
。
否则,请查看Selenium,这是一个网络驱动程序,可让您运行javascript。
希望可以将其清除。
答案 1 :(得分:0)
这适用于您帖子中的两个链接:
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)。